using Dapper;
using DnsClient.Internal;
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,
        IConfiguration configuration,
        ILogger<DenyModelCheckJob> logger)
    {
        this.webConnectionString = configuration.GetConnectionString("WebDBContext");
        this.protalServer = protalServer;
        this.logger = logger;
    }

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

    public async Task Execute(IJobExecutionContext context)
    {
        //logger.LogDebug("{0} Started", nameof(DenyModelCheckJob));
        try
        {
            using (SqlConnection conn = new SqlConnection(webConnectionString))
            {
                string strSql = "SELECT [Value] FROM[StandardOCPP_Web].[dbo].[KernelConfig]" +
                 "where SystemKey = 'DenyModelNames'; ";
                var result = await conn.QueryFirstOrDefaultAsync<string>(strSql);

                GlobalConfig.DenyModelNames = result.Split(',').ToList();
                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));
                    protalServer.RemoveClient(session);
                }
            }
        }
        catch (Exception ex)
        {
            logger.LogError("DenyModelCheckTrigger  Ex:{0}", ex.ToString());
        }
    }
}
