using Common.Constant;
using Common.Logic;
using Database.Database;
using log4net;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SicboSub.Api.DTO;
using SicboSub.Api.Singleton;
using SicboSubWss;
using System.Drawing.Printing;
using System.Net;
using System.ServiceModel;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace SicboSub.Api.Business
{
    public class SubscriptionBusinessImpl : ISubscriptionBusiness
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(SubscriptionBusinessImpl));

        private readonly ModelContext dbContext;
        private readonly IConfiguration configuration;
        SicboSubWss.SicboSubWsClient wsClient;

        string wsUser;
        string wsPass;
        protected void SetWsClient(ref SicboSubWss.SicboSubWsClient wsClient, IConfiguration configuration)
        {
            wsClient.Endpoint.Address = new EndpointAddress(configuration.GetSection("wsUrl").Value);
            log.Info("gds:" + configuration.GetSection("wsUrl").Value);
        }
        public SubscriptionBusinessImpl(ModelContext _dbContext, IConfiguration _configuration)
        {
            dbContext = _dbContext;
            configuration = _configuration;
            wsClient = new SicboSubWss.SicboSubWsClient();
            SetWsClient(ref wsClient, configuration);
            wsUser = GetParameter("wsUser");
            wsPass = GetParameter("wsPass");
        }
        private string GetParameter(string key)
        {
            return configuration.GetSection(key).Value ?? "";
        }
        /// <summary>
        /// Register package
        /// </summary>
        public async Task<IActionResult> Register(HttpRequest httpRequest, RegisterReq request)
        {
            var url = httpRequest.Path;
            var json = JsonConvert.SerializeObject(request);
            log.Debug("URL: " + url + " => Request: " + json);
            string lang = CommonLogic.GetLanguage(httpRequest, request.lang);

            try
            {
                if (string.IsNullOrEmpty(request.msisdn) || string.IsNullOrEmpty(request.packageCode))
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(log, url, json, CommonErrorCode.InvalidParameter, "Missing parameters", new { });
                }

                // Get WS Configs
                
                string serviceId = ConfigManager.Instance.GetConfig("SERVICE_ID");

                string requestId = DateTime.Now.ToString("yyyyMMddHHmmssfff");

                SicboSubWss.wsRegisterSubOtpResponse wsRegisterSubOtpResponse =
                await wsClient.wsRegisterSubOtpAsync(
                       wsUser,
                       wsPass,
                       request.msisdn,
                       request.packageCode,
                       request.packageCode
                );

                var jsonData = JsonConvert.SerializeObject(wsRegisterSubOtpResponse);
                log.Info("request: wsRegisterSubOtpAsync => data: " + jsonData);

                if (wsRegisterSubOtpResponse.@return.errorCode == CommonErrorCode.Success)
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(
                        log, url, json,
                        CommonErrorCode.Success,
                        ConfigManager.Instance.GetConfigWebValue("REGISTER_SUCCESS", lang),
                        new
                        {
                        }
                    );
                  
                }
                else
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(
                        log, url, json,
                        CommonErrorCode.Error,
                        wsRegisterSubOtpResponse.@return.content,
                        new
                        {
                        }
                    );
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception: ", ex);
            }

            return DotnetLib.Http.HttpResponse.BuildResponse(
                log, url, json,
                CommonErrorCode.SystemError,
                ConfigManager.Instance.GetConfigWebValue("SYSTEM_FAILURE"),
                new { }
            );
        }

        /// <summary>
        /// Buy more package
        /// </summary>
        public async Task<IActionResult> BuyMore(HttpRequest httpRequest, BuyMoreReq request)
        {
            var url = httpRequest.Path;
            var json = JsonConvert.SerializeObject(request);
            log.Debug("URL: " + url + " => Request: " + json);
            string lang = CommonLogic.GetLanguage(httpRequest, request.lang);

            try
            {
                if (string.IsNullOrEmpty(request.msisdn) || string.IsNullOrEmpty(request.packageCode))
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(log, url, json, CommonErrorCode.InvalidParameter, "Missing parameters", new { });
                }

                // Get package fee
                var package = dbContext.Packgs.FirstOrDefault(p => p.ProductName == request.packageCode);
                if (package == null)
                {
                     return DotnetLib.Http.HttpResponse.BuildResponse(log, url, json, CommonErrorCode.DataNotFound, "Package not found", new { });
                }
                string fee = package.Fee.ToString();

                // Get WS Configs

                string serviceId = ConfigManager.Instance.GetConfig("SERVICE_ID");

                string requestId = DateTime.Now.ToString("yyyyMMddHHmmssfff");

                SicboSubWss.wsChargeFeeOtpResponse requestRegister =
                    await wsClient.wsChargeFeeOtpAsync(
                        wsUser,
                        wsPass,
                        request.msisdn,
                        package.ProductName,
                        fee,
                        serviceId
                    );

                var jsonData = JsonConvert.SerializeObject(requestRegister);
                log.Info("request: wsChargeFeeOtpAsync => data: " + jsonData);

                if (requestRegister.@return.errorCode == CommonErrorCode.Success)
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(
                        log, url, json,
                        CommonErrorCode.Success,
                        requestRegister.@return.content,
                        new
                        {
                        }
                    );
                }else
                {
                    return DotnetLib.Http.HttpResponse.BuildResponse(
                       log, url, json,
                       CommonErrorCode.Success,
                       requestRegister.@return.content,
                       new
                       {
                       }
                   );
                }
            }
            catch (Exception ex)
            {
                log.Error("Exception: ", ex);
            }

            return DotnetLib.Http.HttpResponse.BuildResponse(
                log, url, json,
                CommonErrorCode.SystemError,
                ConfigManager.Instance.GetConfigWebValue("SYSTEM_FAILURE"),
                new { }
            );
        }
    }
}
