using Newtonsoft.Json;
using NLog;
using NLog.Config;
using ProfitGroup.Rdnl.Extensions;
using ProfitGroup.SampleService.Models;
using RnD.API;
using RnD.BusinessLayer.Interfaces.Model;
using System;
using System.Buffers.Text;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ProfitGroup.SampleService.Core.Services
{
    public class SampleConfirmationService : ISampleConfirmationService
    {
        private Appsettings _appSettings;

        private ILogger Logger
        {
            get
            {
                var loggerConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nlog.config");
                LogManager.Setup().LoadConfigurationFromFile(loggerConfig);
                LogManager.Configuration = new XmlLoggingConfiguration(loggerConfig);

                return LogManager.GetCurrentClassLogger();
            }
        }

        public SampleConfirmationService(RDnLManager manager, API api)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");

            _appSettings = JsonConvert.DeserializeObject<Appsettings>(File.ReadAllText(path));
        }

        public async Task<(bool isSuccess, HttpStatusCode statusCode, string message)> SendConfirmationToSap(MT_InspLot content, SampleFullDTO sampleFullDto,
            bool isSuccessCreated, string message = null)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = BasicAuthorization(_appSettings.ConfirmationLogin, _appSettings.ConfirmationPassword);
                    client.DefaultRequestHeaders.Add("SOAPAction", " http://sap.com/xi/WebService/soap1.1 ");

                    if (string.IsNullOrEmpty(message))
                        message = isSuccessCreated ? $@"Проба сформирована успешно" : "Проба не была сформирована";

                    client.BaseAddress = new Uri(_appSettings.ConfirmationUrl);

                    var dto = new Models.Confirmation.Document
                    {
                        Status = isSuccessCreated ? "S" : "E",
                        StatusText = message,
                        SC_VALUE = sampleFullDto?.ID.Value.ToString() ?? string.Empty,
                        ControlPartionId = content?.Document?.InspectionLot,
                        LineId = "1",
                        ProbeId = content?.Document?.Proba
                    };

                    var data = new Models.Confirmation.Envelope
                    {
                        Body = new Models.Confirmation.EnvelopeBody
                        {
                            MT_InspLotConf = new Models.Confirmation.MT_InspLotConf
                            {
                                Document = dto,
                                GuidMsgOutb = content?.GuigMsgOutb
                            }
                        }
                    };

                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    namespaces.Add("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
                    namespaces.Add("orm", "http://lukoil.ru/opcenter/ORM");

                    var serializer = new XmlSerializer(typeof(Models.Confirmation.Envelope));

                    using (var stringWriter = new StringWriterUTF8())
                    {
                        serializer.Serialize(stringWriter, data, namespaces);

                        var xmlString = stringWriter.ToString();

                        if (Directory.Exists(_appSettings.XmlConfirmationDirectory) == false)
                            Directory.CreateDirectory(_appSettings.XmlConfirmationDirectory);

                        if (!string.IsNullOrEmpty(content.GuigMsgOutb))
                            File.WriteAllText(Path.Combine(_appSettings.XmlConfirmationDirectory, $"{content.GuigMsgOutb}.xml"), xmlString);
                        else
                            Logger.Error($"Был получен пустой Message guid");


                        // ToDo: Заменить ендпоинт
                        
                        //Dev
                        var request = await client.PostAsync("/XISOAPAdapter/MessageServlet?senderParty=&senderService=BSD_OPCENTER&receiverParty=&receiverService=&interface=SI_OpCenterSend_AO&interfaceNamespace=http%3A%2F%2Flukoil.ru%2Fopcenter%2FORM", new StringContent(xmlString, Encoding.UTF8, "text/xml"));
                        
                        //Prod
                        // var request = await client.PostAsync("/XISOAPAdapter/MessageServlet?senderParty=&senderService=BSP_OPCENTER&receiverParty=&receiverService=&interface=SI_OpCenterSend_AO&interfaceNamespace=http://lukoil.ru/opcenter/ORM", new StringContent(xmlString, Encoding.UTF8, "text/xml"));
                        
                        //Test
                        // var request = await client.PostAsync("/MessageServlet?senderParty=&senderService=BST_OPCENTER&receiverParty=&receiverService=&interface=SI_OpCenterSend_AO&interfaceNamespace=http%3A%2F%2Flukoil.ru%2Fopcenter%2FORM", new StringContent(xmlString, Encoding.UTF8, "text/xml"));

                        var result = await request.Content.ReadAsStringAsync();

                        return (request.IsSuccessStatusCode, request.StatusCode, result);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return (false, HttpStatusCode.NoContent, string.Empty);
            }


        }

        public AuthenticationHeaderValue BasicAuthorization(string login, string password)
        {

            var authenticationString = $"{login}:{password}";
            var base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.ASCII.GetBytes(authenticationString));
            return new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
        }
    }
}