using EVCB_OCPP.Domain;
using EVCB_OCPP.Domain.Models.Database;
using EVCB_OCPP.WSServer.Helper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OCPPPackage.Profiles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EVCB_OCPP.WSServer.Service;

public interface IMainDbService
{
    Task<string> GetMachineAuthorizationKey(string ChargeBoxId);
    Task<string> GetMachineConfiguration(string ChargeBoxId, string configName);
    Task<string> GetMachineHeartbeatInterval(string ChargeBoxId);
    Task<MachineAndCustomerInfo> GetMachineIdAndCustomerInfo(string ChargeBoxId);
    Task<string> GetMachineSecurityProfile(string ChargeBoxId);
    Task UpdateMachineBasicInfo(string ChargeBoxId, Machine machine);
    Task AddOCMF(OCMF oCMF);
    Task<ConnectorStatus> GetConnectorStatus(string ChargeBoxId, int ConnectorId);
    Task UpdateConnectorStatus(string Id, ConnectorStatus connectorStatus);
}

public class MainDbService : IMainDbService
{
    public MainDbService(IDbContextFactory<MainDBContext> contextFactory, IConfiguration configuration)
    {
        this.contextFactory = contextFactory;

        var startupLimit = GetStartupLimit(configuration);
        this.startupSemaphore = new SemaphoreSlim(startupLimit);

        var opLimit = GetOpLimit(configuration);
        this.opSemaphore = new SemaphoreSlim(opLimit);
    }

    private readonly IDbContextFactory<MainDBContext> contextFactory;
    private readonly SemaphoreSlim startupSemaphore;
    private readonly SemaphoreSlim opSemaphore;

    public async Task<MachineAndCustomerInfo> GetMachineIdAndCustomerInfo(string ChargeBoxId)
    {
        using var semaphoreWrapper = await SemaphoreWrapper.WaitAsync(startupSemaphore);
        using var db = contextFactory.CreateDbContext();
        var machine = await db.Machine.Where(x => x.ChargeBoxId == ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefaultAsync();
        if (machine == null)
        {
            return new MachineAndCustomerInfo(string.Empty, Guid.Empty, "Unknown");
        }
        var customerName = await db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefaultAsync();
        return new MachineAndCustomerInfo(machine.Id, machine.CustomerId, customerName);
    }

    public async Task<string> GetMachineConfiguration(string ChargeBoxId, string configName)
    {
        using var semaphoreWrapper = await SemaphoreWrapper.WaitAsync(startupSemaphore);
        using var db = contextFactory.CreateDbContext();
        return await db.MachineConfigurations
            .Where(x => x.ChargeBoxId == ChargeBoxId && x.ConfigureName == configName)
            .Select(x => x.ConfigureSetting).FirstOrDefaultAsync();
    }

    public async Task<string> GetMachineSecurityProfile(string ChargeBoxId)
    {
        return await GetMachineConfiguration(ChargeBoxId, StandardConfiguration.SecurityProfile);
    }

    public async Task<string> GetMachineAuthorizationKey(string ChargeBoxId)
    {
        return await GetMachineConfiguration(ChargeBoxId, StandardConfiguration.AuthorizationKey);
    }

    public async Task<string> GetMachineHeartbeatInterval(string ChargeBoxId)
    {
        return await GetMachineConfiguration(ChargeBoxId, StandardConfiguration.HeartbeatInterval);
    }

    public async Task UpdateMachineBasicInfo(string ChargeBoxId, Machine machine)
    {
        using var semaphoreWrapper = await SemaphoreWrapper.WaitAsync(startupSemaphore);
        using var db = contextFactory.CreateDbContext();
        var _machine = db.Machine.FirstOrDefault(x => x.ChargeBoxId == ChargeBoxId);
        _machine.ChargeBoxSerialNumber = machine.ChargeBoxSerialNumber;
        _machine.ChargePointSerialNumber = machine.ChargePointSerialNumber;
        _machine.ChargePointModel = machine.ChargePointModel;
        _machine.ChargePointVendor = machine.ChargePointVendor;
        _machine.FW_CurrentVersion = machine.FW_CurrentVersion;
        //_machine.Iccid = string.IsNullOrEmpty(_request.iccid) ? string.Empty : _request.iccid;
        _machine.Iccid = DateTime.UtcNow.ToString("yy-MM-dd HH:mm");
        _machine.Imsi = machine.Imsi;
        _machine.MeterSerialNumber = machine.MeterSerialNumber;
        _machine.MeterType = machine.MeterType;

        await db.SaveChangesAsync();
    }

    public async Task AddOCMF(OCMF oCMF)
    {
        using var db = contextFactory.CreateDbContext() ;
        db.OCMF.Add(oCMF);
        await db.SaveChangesAsync();
    }

    public async Task<ConnectorStatus> GetConnectorStatus(string ChargeBoxId,int ConnectorId)
    {
        using var db = contextFactory.CreateDbContext();
        return await db.ConnectorStatus.Where(x => x.ChargeBoxId == ChargeBoxId
                            && x.ConnectorId == ConnectorId).AsNoTracking().FirstOrDefaultAsync();
    }

    public async Task UpdateConnectorStatus(string Id, ConnectorStatus connectorStatus)
    {
        using var db = contextFactory.CreateDbContext();

        ConnectorStatus status = new();

        db.ChangeTracker.AutoDetectChangesEnabled = false;
        db.ConnectorStatus.Attach(status);


        status.CreatedOn = connectorStatus.CreatedOn;
        status.Status = connectorStatus.Status;
        status.ChargePointErrorCodeId = connectorStatus.ChargePointErrorCodeId;
        status.ErrorInfo = connectorStatus.ErrorInfo;
        status.VendorId = connectorStatus.VendorId;
        status.VendorErrorCode = connectorStatus.VendorErrorCode;


        db.Entry(status).Property(x => x.CreatedOn).IsModified = true;
        db.Entry(status).Property(x => x.Status).IsModified = true;
        db.Entry(status).Property(x => x.ChargePointErrorCodeId).IsModified = true;
        db.Entry(status).Property(x => x.ErrorInfo).IsModified = true;
        db.Entry(status).Property(x => x.VendorId).IsModified = true;
        db.Entry(status).Property(x => x.VendorErrorCode).IsModified = true;

        //db.SaveChanges();
        await db.SaveChangesAsync();
    }


    private int GetStartupLimit(IConfiguration configuration)
    {
        var limitConfig = configuration["MainDbStartupLimit"];
        int limit = 5;
        if (limitConfig != default)
        {
            int.TryParse(limitConfig, out limit);
        }
        return limit;
    }
    private int GetOpLimit(IConfiguration configuration)
    {
        var limitConfig = configuration["MainDbOpLimit"];
        int limit = 500;
        if (limitConfig != default)
        {
            int.TryParse(limitConfig, out limit);
        }
        return limit;
    }
}

public record MachineAndCustomerInfo (string MachineId, Guid CustomerId, string CustomerName);