using Dapper;
using DnsClient.Internal;
using EVCB_OCPP.WSServer.Service;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OCPPServer.Protocol;
using Quartz;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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();
            //logger.LogDebug("Current DenyList:[{0}]", string.Join(",", GlobalConfig.DenyModelNames));

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

            Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
            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());
        }
    }
}