using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Net;
using System.ServiceModel;
using CreateLabel_ML.wsFedexTrack;
using CreateLabel_ML.wsRedPack;
using MySqlConnector;
using Newtonsoft.Json;
using RestSharp;
using www.estafeta.com;

namespace ActualizarEstatusPaqueteriaTodos
{
   public class Cotizaciones
   {

      public TrackReply Fedex_Tracking(string tracking_number, string sale_order_id, string reference_order_number)
      {
         ServicePointManager.ServerCertificateValidationCallback +=
            (sender, certificate, chain, sslPolicyErrors) => true;
         var log = new clsLog();
         var ws = new TrackPortTypeClient(new BasicHttpsBinding(BasicHttpsSecurityMode.Transport),
            new EndpointAddress("https://ws.fedex.com:443/web-services/track"));
         var peticion = new TrackRequest
         {
            ClientDetail = new ClientDetail
            {
               AccountNumber = ConfigurationManager.AppSettings["AccountNumber"],
               MeterNumber = ConfigurationManager.AppSettings["MeterNumber"]
            },
            TransactionDetail = new TransactionDetail
            {
               CustomerTransactionId = "*** Track Request using PHP ***"
            },
            WebAuthenticationDetail = new WebAuthenticationDetail
            {
               ParentCredential = new WebAuthenticationCredential
               {
                  Key = ConfigurationManager.AppSettings["ParentKey"],
                  Password = ConfigurationManager.AppSettings["ParentPassword"]
               },
               UserCredential = new WebAuthenticationCredential
               {
                  Key = ConfigurationManager.AppSettings["Key"],
                  Password = ConfigurationManager.AppSettings["Password"]
               }
            },
            Version = new VersionId
            {
               Intermediate = 0,
               Major = 16,
               Minor = 0,
               ServiceId = "trck"
            },
            SelectionDetails = new[]
            {
               new TrackSelectionDetail
               {
                  PackageIdentifier = new TrackPackageIdentifier
                  {
                     Type = TrackIdentifierType.TRACKING_NUMBER_OR_DOORTAG,
                     Value = tracking_number
                  }
               }
            }
         };
         var response = ws.trackAsync(peticion).Result.TrackReply;
         log.AgregaPcgRequest(JsonConvert.SerializeObject(peticion), JsonConvert.SerializeObject(response),
            reference_order_number, sale_order_id, "ActualizadorEstatus Fedex");
         return response;
      }
      public void UpdMerchantOrderHeader(string set, string where)
      {
         var cn = new clsConexion();
         cn.EjecutaConsulta("UPDATE sale_order_header SET " + set + " WHERE " + where, new MySqlParameter[] { }, CommandType.Text);

      }

      public void AddSaleOrderTrackingHistory(string sale_order_id, string carrier_name, string tracking_number, string status_name, DateTime date_tracking)
      {
         var cn = new clsConexion();
         cn.EjecutaConsulta("INSERT INTO sale_order_tracking_history (sale_order_id, carrier_name, tracking_number, status_name, date_tracking, date_created) VALUES (@sale_order_id, @carrier_name, @tracking_number, @status_name, @date_tracking, NOW())",
            new[]
            {
               new MySqlParameter("@sale_order_id",sale_order_id),
               new MySqlParameter("@carrier_name",carrier_name),
               new MySqlParameter("@tracking_number",tracking_number),
               new MySqlParameter("@status_name",status_name),
               new MySqlParameter("@date_tracking",date_tracking)
            }, CommandType.Text);
      }

      public QueryResult GetEstafetaShippingStatus(string tracking_number, string sale_order_id, string reference_order_number)
      {
         ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
         var log = new clsLog();
         var ws = new ServiceSoapClient(new BasicHttpsBinding(BasicHttpsSecurityMode.Transport), new EndpointAddress("https://tracking.estafeta.com/Service.asmx"));
         var peticion = new SearchType
         {
            waybillRange = new WaybillRange
            {
               finalWaybill = tracking_number,
               initialWaybill = tracking_number
            },
            type = "R",
            waybillList = new WaybillList
            {
               waybillType = "R",
               waybills = new ArrayOfString
               {
                  "201505906741C604100756"
               }
            }
         };
         var response = ws.ExecuteQueryAsync("268", "5681045", "DDkDy2HZ0", peticion, new SearchConfiguration
         {
            filterType = new Filter
            {
               filterType = "?",
               filterInformation = false
            },
            includeCustomerInfo = false,
            includeDimensions = false,
            includeInternationalData = false,
            includeMultipleServiceData = false,
            includeReturnDocumentData = false,
            includeSignature = false,
            includeWaybillReplaceData = false,
            historyConfiguration = new HistoryConfiguration
            {
               historyType = "ALL",
               includeHistory = false
            }
         }).Result.Body.ExecuteQueryResult;
         log.AgregaPcgRequest(JsonConvert.SerializeObject(peticion), JsonConvert.SerializeObject(response), reference_order_number, sale_order_id, "ActualizadorEstatus Estafeta");
         return response;
      }

      public clsRespuestaSrEnvios GetSkydropxShipingStatus(string tracking_number, string sale_order_id, string reference_order_number, string carrier)
      {
         var log = new clsLog();
         var wsSrEnvios = new RestClient(ConfigurationManager.AppSettings["UrlSrEnvios"])
         {
            RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
         };
         var enviaSrEnvios = new RestRequest("", Method.POST, DataFormat.Json);
         enviaSrEnvios.AddHeader("Authorization", ConfigurationManager.AppSettings["AuthorizationSrEnvios"]);
         var peticion = new clsSrEnvios
         {
            tracking_numbers = new List<TrackingNumber>(new []
            {
               new TrackingNumber
               {
                  tracking_number = tracking_number,
                  carrier = carrier
               }
            })
         };
         enviaSrEnvios.AddJsonBody(peticion);
         var curlPostSrEnvios = wsSrEnvios.Execute(enviaSrEnvios);
         log.AgregaPcgRequest(JsonConvert.SerializeObject(peticion), curlPostSrEnvios.Content, reference_order_number, sale_order_id, "ActualizadorEstatus Sr. Envios");
         var srenvios_cotizacion = JsonConvert.DeserializeObject<clsRespuestaSrEnvios>(curlPostSrEnvios.Content);
         return srenvios_cotizacion;
      }

      public Guia RedPackStatus(string tracking_number, string sale_order_id, string reference_order_number)
      {
         var log = new clsLog();
         var cn = new clsConexion();
         var id = 0;
         var pin = string.Empty;
         var cliente = string.Empty;
         id = int.Parse(cn.TraeDataTable("SELECT value FROM m_configuration WHERE name='RedPack_ID'", new MySqlParameter[] { }, CommandType.Text).Rows[0][0].ToString());
         pin = cn.TraeDataTable("SELECT value FROM m_configuration WHERE name='RedPack_PIN'", new MySqlParameter[] { }, CommandType.Text).Rows[0][0].ToString();
         cliente = cn.TraeDataTable("SELECT value FROM m_configuration WHERE name='RedPack_Cliente'", new MySqlParameter[] { }, CommandType.Text).Rows[0][0].ToString();
         var ws = new RedpackWSPortTypeClient(new BasicHttpsBinding(BasicHttpsSecurityMode.Transport), new EndpointAddress("https://ws.redpack.com.mx/RedpackAPI_WS/services/RedpackWS.RedpackWSHttpsSoap11Endpoint"));
         var guias = new List<Guia>
         {
            new Guia
            {
               moneda = cliente,
               numeroDeGuia = tracking_number,
               referencia = sale_order_id,
               flag = 0,
               flagSpecified = true
            }
         };
         var guia = ws.rastreoAsync(pin, id, guias.ToArray()).Result.@return[0];
         log.AgregaPcgRequest(JsonConvert.SerializeObject(guias), JsonConvert.SerializeObject(guia), reference_order_number, sale_order_id, "ActualizadorEstatus RedPack");
         return guia;
      }
      public clsRespuestaEstatusIEnvios IEnviosStatus(string tracking_number, string sale_order_id, string reference_order_number)
      {
         var respuesta = string.Empty;
         var log = new clsLog();
         try
         {
            var cn = new clsConexion();
            var dt = cn.TraeDataTable("SELECT value FROM m_configuration WHERE name = 'ENDPOINT_iENVIOSStatus';", new MySqlParameter[] { }, CommandType.Text);
            var client = new RestClient(dt.Rows[0]["value"].ToString());
            var request = new RestRequest("?folio_orden=" + tracking_number, Method.GET, DataFormat.Json);
            request.AddHeader("Authorization", ConfigurationManager.AppSettings["AuthorizationIEnvios"]);
            var response = client.Execute(request);
            respuesta = response.Content;
            log.AgregaPcgRequest(dt.Rows[0]["value"] + "?folio_orden=" + tracking_number, response.Content, reference_order_number, sale_order_id, "ActualizadorEstatus iEnvios");
            var r = JsonConvert.DeserializeObject<clsRespuestaEstatusIEnvios>(respuesta);
            return r;
         }
         catch (Exception ex)
         {
            log.EscribeLog("Error: "+ex.Message);
            return null;
         }
      }
   }
}
