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

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EVCB_OCPP.WSServer.Jobs;

[DisallowConcurrentExecution]
public class HealthCheckTriggerJob : IJob
{
    public HealthCheckTriggerJob(
        ProtalServer protalServer,
        ILogger<HealthCheckTriggerJob> logger)
    {
        this.protalServer = protalServer;
        this.logger = logger;
    }

    private readonly ProtalServer protalServer;
    private readonly ILogger<HealthCheckTriggerJob> logger;

    public Task Execute(IJobExecutionContext context)
    {
        //logger.LogDebug("{0} Started", nameof(HealthCheckTriggerJob));

        Dictionary<string, WsClientData> _copyClientDic = protalServer.GetClientDic();

        var removeClients = _copyClientDic.Where(x => x.Value.LastActiveTime < DateTime.UtcNow.AddSeconds(-300)).Select(x => x.Value).ToList();

        foreach (var session in removeClients)
        {
            logger.LogDebug("Server forced to shut down ChargeBox ({0}: LastActiveTime{1})", session.ChargeBoxId, session.LastActiveTime);
            protalServer.RemoveClient(session, "Inactive");
        }
        return Task.CompletedTask;
    }
}