using HTCoreServiceApp.Common;
using HTCoreServiceApp.DataHandle;
using HTCoreServiceApp.WebApi;
using Microsoft.AspNetCore.Http.Headers;
using Microsoft.AspNetCore.Http.HttpResults;
using SqlSugar;
using System.Text.Json.Serialization;

namespace HTCoreServiceApp
{
	public class Program
	{
		public static void Main(string[] args)
		{
			var builder = WebApplication.CreateSlimBuilder(args);

			builder.Services.ConfigureHttpJsonOptions(options =>
			{
				options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
			});

			/*************启用SqlSugar的AOT*******************/
			StaticConfig.EnableAot = true;

			IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
			builder.Services.AddSingleton(new ConfigHelper(configuration));

			builder.Services.AddSingleton(new DriverService());

			builder.WebHost.UseUrls($"http://*:{builder.Configuration.GetSection("ServiceHostPort").Value}");

			//builder.WebHost.UseWebRoot($"http://*:{builder.Configuration.GetSection("ServiceHostPort").Value}");

			//builder.Services.AddControllers();

			builder.Services.AddStackExchangeRedisCache(options =>
			{
				options.Configuration = "localhost:3069";
				options.InstanceName = "test";
			});

			builder.Services.AddMemoryCache(options =>
			{
				options.TrackLinkedCacheEntries = true;
				options.ExpirationScanFrequency = TimeSpan.FromSeconds(1);
				options.TrackStatistics = true;
				options.SizeLimit = 10000;
			});

			//builder.Services.AddEndpointsApiExplorer();

			builder.Services.AddTransient<DataLiveCache>();//禁开api单例测试速度 
			builder.Services.AddTransient<DataExtract>();
			builder.Services.AddSingleton<DeviceControl>();


			var app = builder.Build();

            #region 带节点api
            var dataLiveCacheApi = app.MapGroup("/DataLiveCache");
			dataLiveCacheApi.MapGet("/Get",
				async(DataLiveCache dlc) 
				=> Results.Content(await dlc.Get()));

			dataLiveCacheApi.MapGet("/{Name}", 
				async (string Name, DataLiveCache dlc) 
				=> Results.Content(await dlc.GetName(Name)));

            dataLiveCacheApi.MapGet("/GetLiveSystemData/systemName={systemName}",
                async (string systemName, DataLiveCache dlc)
                => Results.Content(await dlc.GetLiveSystemData(systemName)));

            dataLiveCacheApi.MapGet("/GetLiveDriverData/driverName={driverName}",
                async (string driverName, DataLiveCache dlc)
                => Results.Content(await dlc.GetLiveDriverData(driverName)));

            dataLiveCacheApi.MapGet("/GetLiveGroupData/groupName={groupName}",
				async (string groupName, DataLiveCache dlc) 
				=> Results.Content(await dlc.GetLiveGroupData(groupName)));

			dataLiveCacheApi.MapGet("/GetLiveTagData/groupName={groupName}&tagName={tagName}",
				async (string groupName, string tagName, DataLiveCache dlc) 
				=> Results.Content(await dlc.GetLiveTagData(groupName,tagName)));
            #endregion

            #region 无节点api
            dataLiveCacheApi.MapGet("/GetLiveSystemAllData/AllSystem",
                async (DataLiveCache dlc)
                => Results.Content(await dlc.GetLiveAllSystemData()));

            dataLiveCacheApi.MapGet("/GetLiveSystemAllData/systemName={systemName}",
                async (string systemName, DataLiveCache dlc)
                => Results.Content(await dlc.GetLiveSystemAllData(systemName)));

            dataLiveCacheApi.MapGet("/GetLiveDriverAllData/driverName={driverName}",
                async (string driverName, DataLiveCache dlc)
                => Results.Content(await dlc.GetLiveDriverAllData(driverName)));

            dataLiveCacheApi.MapGet("/GetLiveGroupAllData/groupName={groupName}",
                async (string groupName, DataLiveCache dlc)
                => Results.Content(await dlc.GetLiveGroupAllData(groupName)));
            #endregion

            #region 自由组合api
            dataLiveCacheApi.MapGet("/GetLiveCustomData/ApiName={ApiName}",
                async (string ApiName, DataLiveCache dlc)
                => Results.Content(await dlc.GetLiveCustomData(ApiName)));
            #endregion

            #region 写入api
            var deviceControl = app.MapGroup("/DeviceControl");
            deviceControl.MapGet("/Get",
				async (DeviceControl dc)
				=> Results.Content(await dc.Get()));

			deviceControl.MapGet("/{Name}",
				async (string Name, DeviceControl dc)
				=> Results.Content(await dc.GetName(Name)));

			deviceControl.MapGet("/SetDeviceData/groupName={groupName}&tagName={tagName}&value={value}",
				async (string groupName, string tagName ,string value,DeviceControl dc)
				=> Results.Content(await dc.SetDeviceData(groupName, tagName, value)));

            deviceControl.MapGet("/SetDeviceTagData/tagName={tagName}&value={value}",
                async (string tagName, string value,HttpContext context, DeviceControl dc)
                => Results.Content(await dc.SetDeviceTagData(tagName, value ,context)));

            deviceControl.MapGet("/SetDeviceBlockData/driverName={driverName}&address={address}&value={value}",
                async (string driverName, string address, string value, DeviceControl dc)
                => Results.Content(await dc.SetDeviceBlockData(driverName, address, value)));

            var sampleTodos = new Todo[] {
				new(1, "Walk the dog"),
				new(2, "Do the dishes", DateOnly.FromDateTime(DateTime.Now)),
				new(3, "Do the laundry", DateOnly.FromDateTime(DateTime.Now.AddDays(1))),
				new(4, "Clean the bathroom"),
				new(5, "Clean the car", DateOnly.FromDateTime(DateTime.Now.AddDays(2)))
			};

			var todosApi = app.MapGroup("/todos");
			todosApi.MapGet("/", () => sampleTodos);
			todosApi.MapGet("/{id}", (int id) =>
				sampleTodos.FirstOrDefault(a => a.Id == id) is { } todo
					? Results.Ok(todo)
					: Results.NotFound());

            #endregion

            app.Run();
		}
	}

	public record Todo(int Id, string? Title, DateOnly? DueBy = null, bool IsComplete = false);

	[JsonSerializable(typeof(Todo[]))]
	internal partial class AppJsonSerializerContext : JsonSerializerContext
	{

	}

}
