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.IO;
using System.Net;
using System.Net.Http;
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> SendConfirmationToSap(MT_InspLot content, SampleFullDTO sampleFullDto, bool isSuccessCreated)
        {
            try
            {
                using (var client = new HttpClient())
                {

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

                    var dto = new Models.Confirmation.Document
                    {
                        Status = isSuccessCreated ? "S" : "E",
                        StatusText = isSuccessCreated ? $@"Проба сформирована успешно" : "Проба не была сформирована",
                        SC_VALUE = sampleFullDto.ShortDescription,
                        ControlPartionId = content.Document.InspectionLot,
                        LineId = "1",
                        ProbeId = sampleFullDto.ID.ToString()
                    };

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

                    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 StringWriter())
                    {


                        serializer.Serialize(stringWriter, data, namespaces);

                        var xmlString = stringWriter.ToString();
                        // ToDo: Заменить ендпоинт
                        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));

                        return request.IsSuccessStatusCode;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return false;
            }


        }
    }
}