using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Net.WebSockets;
using System.Text;

namespace EVCB_OCPP.WSServer.Service.WsService;

public static partial class AppExtention
{
    public static void AddOcppWsServer(this IServiceCollection services)
    {
        services.AddTransient<WsClientData>();
        services.AddSingleton<OcppWebsocketService>();
    }

    public static void UseOcppWsService(this WebApplication webApplication)
    {
        webApplication.UseWebSockets(new WebSocketOptions()
        {
            KeepAliveInterval = TimeSpan.FromSeconds(10)
        });

        webApplication.Use(async (context, next) =>
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await next(context);
                return;
            }

            var servcie = context.RequestServices.GetService<OcppWebsocketService>();
            await servcie.AcceptWebSocket(context);
            return;
        });
    }
}

public class OcppWebsocketService : WebsocketService<WsClientData>
{
    public static List<string> protocals = new List<string>() { "", "ocpp1.6", "ocpp2.0.1" };

    private readonly IConfiguration configuration;
    private readonly IMainDbService mainDbService;
    private readonly ILogger<OcppWebsocketService> logger;

    public OcppWebsocketService(
        IConfiguration configuration,
        IServiceProvider serviceProvider,
        IMainDbService mainDbService,
        ILogger<OcppWebsocketService> logger
        ) : base(serviceProvider)
    {
        this.configuration = configuration;
        this.mainDbService = mainDbService;
        this.logger = logger;
    }

    internal override async ValueTask<string> ValidateSupportedPortocol(HttpContext context)
    {
        logger.LogInformation("{id} {function}:{Path}/{SubProtocol}", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path, context.WebSockets.WebSocketRequestedProtocols);

        var protocol = GetSupportedPortocol(context.WebSockets.WebSocketRequestedProtocols, protocals);
        if (string.IsNullOrEmpty(protocol))
        {
            logger.LogInformation("{id} {function}:{Path} Protocol Not Supported, Disconnecting", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path);

            using WebSocket toRejectwebSocket = await context.WebSockets.AcceptWebSocketAsync();
            await toRejectwebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default);
            return string.Empty;
        }
        return protocol;
    }

    internal override async ValueTask<bool> ValidateHandshake(HttpContext context, WsClientData session)
    {
        string authHeader = context?.Request?.Headers?.Authorization;

        session.ISOCPP20 = context.WebSockets.WebSocketRequestedProtocols.Any(x => x.ToLower() == "ocpp2.0");

        int securityProfile = 0;
        string authorizationKey = string.Empty;
        if (string.IsNullOrEmpty(session.Path))
        {
            //logger.Log();
            logger.LogWarning("===========================================");
            logger.LogWarning("{id} session.Path EMPTY", context.TraceIdentifier);
            logger.LogWarning("===========================================");
        }

        string[] words = session.Path.ToString().Split('/');
        session.ChargeBoxId = words.Last();
        logger.LogDebug("{id} {0}:{1}", context.TraceIdentifier, session.ChargeBoxId, session.UriScheme);

        foreach (var denyModel in GlobalConfig.DenyModelNames)
        {
            if (string.IsNullOrEmpty(denyModel))
            {
                continue;
            }

            if (session.ChargeBoxId.StartsWith(denyModel))
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;

                logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
                return false;
            }
        }

        if (configuration["MaintainMode"] == "1")
        {
            session.ChargeBoxId = session.ChargeBoxId + "_2";
        }

        logger.LogInformation("{id} ValidateHandshake: {0}", context.TraceIdentifier, session.Path);
        bool isExistedSN = false;
        bool authorizated = false;

        var info = await mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId);
        //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
        //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
        //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
        //session.MachineId = machine == null ? String.Empty : machine.Id;
        //isExistedSN = machine == null ? false : true;
        session.CustomerName = info.CustomerName;
        session.CustomerId = info.CustomerId;
        session.MachineId = info.MachineId;
        isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;

        if (!isExistedSN)
        {
            context.Response.StatusCode = StatusCodes.Status404NotFound;
            logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
            return false;
        }

        //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
        //                  .Select(x => x.ConfigureSetting).FirstOrDefault();
        var configVaule = mainDbService.GetMachineSecurityProfile(session.ChargeBoxId).Result;
        int.TryParse(configVaule, out securityProfile);

        if (session.ISOCPP20)
        {
            // 1.6 server only support change server  function
            securityProfile = 0;
        }

        if (securityProfile == 3 && session.UriScheme == "ws")
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
            return false;
        }

        if (securityProfile == 1 || securityProfile == 2)
        {
            if (securityProfile == 2 && session.UriScheme == "ws")
            {
                authorizated = false;
            }

            //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
            if (!string.IsNullOrEmpty(authHeader))
            {
                //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
                //                    .Select(x => x.ConfigureSetting).FirstOrDefault();
                authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId);

                if (session.ISOCPP20)
                {
                    // 1.6 server only support change server  function
                    securityProfile = 0;
                }

                logger.LogInformation("{id} ***********Authorization   ", context.TraceIdentifier);

                if (!string.IsNullOrEmpty(authorizationKey))
                {
                    //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
                    string base64Encoded = authHeader.Replace("Basic ", "");
                    byte[] data = Convert.FromBase64String(base64Encoded);
                    string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
                    logger.LogInformation("{id} ***********Authorization   " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
                    if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
                    {
                        authorizated = true;
                    }
                }
            }
            else
            {
                authorizated = true;

            }

            if (!authorizated)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
                return false;
            }
        }

        logger.LogInformation("{id} ValidateHandshake PASS: {0}", context.TraceIdentifier, session.Path);
        return true;
    }

    private static string GetSupportedPortocol(IList<string> clientProtocols, IList<string> supportedProtocols)
    {
        int supportedProtocolIndex = supportedProtocols.Count - 1;
        for (; supportedProtocolIndex >= 0; supportedProtocolIndex--)
        {
            var testProtocol = supportedProtocols[supportedProtocolIndex];
            if (clientProtocols.Contains(testProtocol))
            {
                return testProtocol;
            }
        }
        return string.Empty;
    }
}
