using EVCB_OCPP.WSServer.Message;
using EVCB_OCPP.WSServer.Service;
using Microsoft.Data.SqlClient;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EVCB_OCPP.WSServer.Dto;
using Microsoft.Extensions.Configuration;
using Dapper;
using Microsoft.Extensions.Logging;

namespace EVCB_OCPP.WSServer.Jobs;

[DisallowConcurrentExecution]
public class SmartChargingJob : IJob
{
    public SmartChargingJob(
        ProtalServer protalServer,
        IConfiguration configuration,
        ILogger<SmartChargingJob> logger)
    {
        this.webConnectionString = configuration.GetConnectionString("WebDBContext");
        this.protalServer = protalServer;
        this.logger = logger;
    }

    private readonly string webConnectionString;
    private readonly ProtalServer protalServer;
    private readonly ILogger<SmartChargingJob> logger;
    private static List<StationInfoDto> _StationInfo = new List<StationInfoDto>();

    public async Task Execute(IJobExecutionContext context)
    {
        logger.LogDebug("{0} Started", nameof(SmartChargingJob));
        List<StationInfoDto> stations = null;
        using (SqlConnection conn = new SqlConnection(webConnectionString))
        {
            string strSql = "SELECT[Id],[LBMode],[LBCurrent] as Availability FROM[StandardOCPP_Web].[dbo].[Station]" +
             "where LBMode = 1; ";
            var result = await conn.QueryAsync<StationInfoDto>(strSql);
            stations = result.ToList();
        }
        foreach (var station in stations)
        {
            var compareStation = _StationInfo.Where(x => x.Id == station.Id).FirstOrDefault();

            if (compareStation != null && (station.Id != compareStation.Id || station.Availability == compareStation.Availability))
            {
                continue;
            }
            var _powerDic = await protalServer.LoadingBalanceService.GetSettingPower(station.Id);
            if (_powerDic == null)
            {
                continue;
            }
            foreach (var kv in _powerDic)
            {
                try
                {

                    if (kv.Value.HasValue)
                    {
                        protalServer.ProfileHandler.SetChargingProfile(kv.Key, kv.Value.Value, Packet.Messages.SubTypes.ChargingRateUnitType.W);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError("Set Profile Exception: {0}", ex.ToString());
                }

            }
        }
        _StationInfo = stations;
    }
}