using EVCB_OCPP.WSServer.Service;
using EVCB_OCPP.WSServer.Service.WsService;
using Microsoft.Extensions.Logging;
using Quartz;

namespace EVCB_OCPP.WSServer.Jobs;

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

    //private readonly string webConnectionString;
    private readonly ProtalServer protalServer;
    private readonly WebDbService webDbService;
    private readonly ILogger<DenyModelCheckJob> logger;

    public async Task Execute(IJobExecutionContext context)
    {
        //logger.LogDebug("{0} Started", nameof(DenyModelCheckJob));
        try
        {
            GlobalConfig.DenyModelNames = await webDbService.GetDenyModelNames(context.CancellationToken);
            logger.LogDebug("Current DenyList:[{0}]", string.Join(",", GlobalConfig.DenyModelNames));

            if (string.IsNullOrEmpty(GlobalConfig.DenyModelNames[0]))
            {
                return;
            }

            Dictionary<string, WsClientData> _copyClientDic = protalServer.GetClientDic();
            foreach (var denyName in GlobalConfig.DenyModelNames)
            {
                var removeClients = _copyClientDic.Where(x => x.Key.StartsWith(denyName)).Select(x => x.Value).ToList();
                foreach (var session in removeClients)
                {
                    //Console.WriteLine(string.Format("Server forced to shut down ChargeBox ({0}: Reason: DenyModelName-{1}", session.ChargeBoxId, denyName));
                    logger.LogInformation(string.Format("Server forced to shut down ChargeBox ({0}: Reason: DenyModelName-{1}", session.ChargeBoxId, denyName));
                    protalServer.RemoveClient(session);
                }
            }
        }
        catch (Exception ex)
        {
            logger.LogError("DenyModelCheckTrigger  Ex:{0}", ex.ToString());
        }
    }
}
