using Masuit.Tools;
using Masuit.Tools.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using PVDEMCS;
using PVDEMCS.Common.DI;
using PVDEMCS.Common.Log;
using PVDEMCS.Devices;
using PVDEMCS.Services;
using System.Configuration;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    //options.SwaggerDoc("v1", new OpenApiInfo { Title = "PVDEMCS Api", Version = "v1" });
    var xmlPathApp = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
    options.IncludeXmlComments(xmlPathApp, true);
});
//添加跨域策略
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});

//注册服务
builder.AddAutofacExt();
//
//builder.Services.AddDbContext<EFContext>(options =>
//{
//    options.UseMySQL(builder.Configuration.GetConnectionString("MySqlConnection"));
//});
var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{

//}

app.UseSwagger();
app.UseSwaggerUI();

//使用跨域策略
app.UseCors("CorsPolicy");

//app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Lifetime.ApplicationStarted.Register(() =>
{
    var logService = app.Services.GetService<ILogService>();

    LogExtensions.Load(logService);

    var deviceRun = app.Services.GetService<IDeviceRun>();

    deviceRun.Run();

    //var equipmentList = app.Services.GetService<IEquipmentService>();
    //var equipmentRecord = app.Services.GetService<IEquipmentRecordService>();
    //var ids = equipmentList.GetEquipmentList().Content.Select(f => f.Id).ToList();
    //var startDate = DateTime.Parse("2023-01-01");
    //var obj = new object();

    //var result = System.Threading.Tasks.Parallel.ForEach(ids, id =>
    // {
    //     Test.CreateData(startDate, id, (id, state, dt) =>
    //     {
    //         lock (obj)
    //         {
    //             equipmentRecord.AddUpdateEquipmentRecord(id, state, dt);
    //         }
    //     });
    // });


    //while (true)
    //{
    //    if (startDate > DateTime.Now)
    //    {
    //        return;
    //    }
    //    equipmentRecord.RunEquipmentRecordDayTotal(startDate);
    //    startDate = startDate.AddDays(1);

    //    Thread.Sleep(100);
    //}

});

app.Run();
