using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.ServiceModel;
using ActualizarEstatusPaqueteria;
using MySqlConnector;

namespace CreateLabel_ML
{
   public class Program
   {
      public static void Main(string[] args)
      {
         var log = new clsLog();
         try
         {
            var cotizaciones = new Cotizaciones();
            var query = ConfigurationManager.AppSettings["SPConsulta"];
            var cont = 0;
            var cn = new clsConexion();
            var data = cn.TraeDataSet(query, new MySqlParameter[] { }, CommandType.StoredProcedure).Tables[0];
            log.EscribeLog(data.Rows.Count + " pedidos.");
            string[] estatuscompletado;
            foreach (DataRow order in data.Rows)
            {
               log.EscribeLog("----------");
               log.EscribeLog("Consulta estatus "+ order["carrier_name"].ToString().ToUpper() + ".");
               // validamos por paqueteria
               switch (order["carrier_name"].ToString().ToUpper())
               {
                  case "FEDEX":
                     #region Fedex
                     var shipping_status = cotizaciones.Fedex_Tracking(order["tracking_number"].ToString(), order["sale_order_id"].ToString(), order["reference_order_number"].ToString());
                     if (shipping_status.HighestSeverity == wsFedexTrack.NotificationSeverityType.SUCCESS)
                     {
                        if (shipping_status.CompletedTrackDetails[0].HighestSeverity == wsFedexTrack.NotificationSeverityType.SUCCESS)
                        {
                           if (shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail != null)
                           {
                              // se cambia estatus en merch
                              ValidaEntregado(new[]
                              {
                                 "DL",
                                 "IT",
                                 "AR",
                                 "SE",
                                 "DP"
                              }, shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail.Code, order["reference_order_number"].ToString());
                              cotizaciones.UpdMerchantOrderHeader("carrier_shipping_status='" + shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail.Description + "', carrier_date_tracking='" + shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail.CreationTime.ToString("yyyy-MM-dd HH:mm:ss") + "'", "reference_order_number='" + order["reference_order_number"] + "'");
                              cotizaciones.AddSaleOrderTrackingHistory(order["sale_order_id"].ToString(), order["carrier_name"].ToString(), order["tracking_number"].ToString(), shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail.Description, shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail.CreationTime);
                              log.EscribeLog("Pedido: " + order["reference_order_number"]);
                              log.EscribeLog("Estatus anterior: " + order["shipping_status"]);
                              log.EscribeLog("Estatus nuevo: " + shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail.Code + " (" + shipping_status.CompletedTrackDetails[0].TrackDetails[0].StatusDetail.Description + ")");
                              log.EscribeLog("Guia: " + order["tracking_number"]);
                           }
                           else
                           {
                              log.EscribeLog("Error al consultar estatus Fedex.");
                              log.EscribeLog("Pedido: " + order["reference_order_number"]);
                              log.EscribeLog("Guia: " + order["tracking_number"]);
                           }
                        }
                        else
                        {
                           log.EscribeLog("Error al consultar estatus Fedex.");
                           log.EscribeLog("Pedido: " + order["reference_order_number"]);
                           log.EscribeLog("Guia: " + order["tracking_number"]);
                        }
                     }
                     else
                     {
                        log.EscribeLog("Error al consultar estatus Fedex.");
                        log.EscribeLog("Pedido: " + order["reference_order_number"]);
                        log.EscribeLog("Guia: " + order["tracking_number"]);
                     }
                     #endregion
                     break;
                  case "ESTAFETA":
                     #region Estafeta
                     var xml_response = cotizaciones.GetEstafetaShippingStatus(order["tracking_number"].ToString(),order["sale_order_id"].ToString(),order["reference_order_number"].ToString());
                     var errorCode = xml_response.errorCode;
                     if (string.Compare(errorCode, "0",StringComparison.CurrentCultureIgnoreCase)!=0)
                     {
                        log.EscribeLog("Error al consultar estatus Estafeta.");
                        log.EscribeLog("Pedido: " + order["reference_order_number"]);
                        log.EscribeLog("Guia: " + order["tracking_number"]);
                     }
                     else
                     {
                        if (xml_response.trackingData.Length > 0)
                        {
                           var status_code = xml_response.trackingData[0].statusSPA;
                           ValidaEntregado(new[] { "CONFIRMADO" }, status_code, order["reference_order_number"].ToString());
                           var date_delivery = xml_response.trackingData[0].deliveryData.deliveryDateTime;
                           var newformat = string.Empty;
                           if (date_delivery.Trim().Length > 0)
                           {
                              date_delivery = date_delivery.Substring(0, 10);
                              newformat = "'" + date_delivery.Substring(6, 4) + "-" + date_delivery.Substring(3, 2) + "-" + date_delivery.Substring(0, 2) + "'";
                           }
                           else
                              newformat = "NULL";
                           cotizaciones.UpdMerchantOrderHeader("carrier_shipping_status='" + status_code + "', carrier_date_tracking=" + newformat, "reference_order_number='" + order["reference_order_number"] + "'");
                           cotizaciones.AddSaleOrderTrackingHistory(order["sale_order_id"].ToString(), order["carrier_name"].ToString(), order["tracking_number"].ToString(), status_code, date_delivery.Trim().Length > 0 ? DateTime.Parse(newformat) : DateTime.Now);
                           log.EscribeLog("Pedido: " + order["reference_order_number"]);
                           log.EscribeLog("Estatus anterior: " + order["shipping_status"]);
                           log.EscribeLog("Estatus nuevo: " + status_code);
                           log.EscribeLog("Guia: " + order["tracking_number"]);
                        }
                        else
                        {
                           log.EscribeLog("Error al consultar estatus Estafeta.");
                           log.EscribeLog("Pedido: " + order["reference_order_number"]);
                           log.EscribeLog("Guia: " + order["tracking_number"]);
                        }
                     }
                     #endregion
                     break;
                  case "PAQUETEXPRESS":
                     #region PaquetExpress
                     var respuestaSrEnvios = cotizaciones.GetSkydropxShipingStatus(order["tracking_number"].ToString(), order["sale_order_id"].ToString(), order["reference_order_number"].ToString(),order["carrier_name"].ToString());
                     if (respuestaSrEnvios==null|| respuestaSrEnvios.data.Count==0)
                     {
                        log.EscribeLog("Error al consultar estatus Sr. Envios.");
                        log.EscribeLog("Pedido: " + order["reference_order_number"]);
                        log.EscribeLog("Guia: " + order["tracking_number"]);
                     }
                     else
                     {
                        ValidaEntregado(new[]
                        {
                           "DELIVERED",
                           "IN_TRANSIT",
                           "LAST_MILE",
                           "DELIVERY_ATTEMPT"
                        }, respuestaSrEnvios.data[0].status, order["reference_order_number"].ToString());
                        log.EscribeLog("Pedido: " + order["reference_order_number"]);
                        log.EscribeLog("Estatus anterior: " + order["shipping_status"]);
                        log.EscribeLog("Estatus nuevo: " + respuestaSrEnvios.data[0].status);
                        log.EscribeLog("Guia: " + order["tracking_number"]);
                        cotizaciones.UpdMerchantOrderHeader("carrier_shipping_status='" + respuestaSrEnvios.data[0].status+ "', carrier_date_tracking='"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"'", "reference_order_number='" + order["reference_order_number"] + "'");
                        cotizaciones.AddSaleOrderTrackingHistory(order["sale_order_id"].ToString(), order["carrier_name"].ToString(), order["tracking_number"].ToString(), respuestaSrEnvios.data[0].status, DateTime.Now);
                     }
                     #endregion
                     break;
                  case "REDPACK":
                     #region RedPack
                     var respuestaRedPack = cotizaciones.RedPackStatus(order["tracking_number"].ToString(), order["sale_order_id"].ToString(), order["reference_order_number"].ToString());
                     if (respuestaRedPack == null)
                     {
                        log.EscribeLog("Error al consultar estatus RedPack.");
                        log.EscribeLog("Pedido: " + order["reference_order_number"]);
                        log.EscribeLog("Guia: " + order["tracking_number"]);
                     }
                     else
                     {
                        if (respuestaRedPack.paquetes[0] != null)
                        {
                           ValidaEntregado(new []{ "ENTREGADO" }, respuestaRedPack.paquetes[0].detallesRastreo[0].evento, order["reference_order_number"].ToString());
                           log.EscribeLog("Pedido: " + order["reference_order_number"]);
                           log.EscribeLog("Estatus anterior: " + order["shipping_status"]);
                           log.EscribeLog("Estatus nuevo: " + respuestaRedPack.paquetes[0].detallesRastreo[0].evento);
                           log.EscribeLog("Guia: " + order["tracking_number"]);
                           cotizaciones.UpdMerchantOrderHeader("carrier_shipping_status='" + respuestaRedPack.paquetes[0].detallesRastreo[0].evento +  "', carrier_date_tracking='" + (respuestaRedPack.paquetes[0].detallesRastreo[0].fechaEvento.Value == null ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : respuestaRedPack.paquetes[0].detallesRastreo[0].fechaEvento.Value.ToString("yyyy-MM-dd HH:mm:ss")) + "'", "reference_order_number='" + order["reference_order_number"] + "'");
                           cotizaciones.AddSaleOrderTrackingHistory(order["sale_order_id"].ToString(), order["carrier_name"].ToString(), order["tracking_number"].ToString(), respuestaRedPack.paquetes[0].detallesRastreo[0].evento ,
                              (respuestaRedPack.paquetes[0].detallesRastreo[0].fechaEvento.Value == null
                                 ? DateTime.Now
                                 : respuestaRedPack.paquetes[0].detallesRastreo[0].fechaEvento.Value));
                        }
                        else
                        {
                           log.EscribeLog("Error al consultar estatus RedPack.");
                           log.EscribeLog("Pedido: " + order["reference_order_number"]);
                           log.EscribeLog("Guia: " + order["tracking_number"]);
                        }
                     }
                     #endregion
                     break;
                  case "IENVIOS":
                     #region iEnvios
                     var respuestaiEnvios = cotizaciones.IEnviosStatus(order["tracking_number"].ToString(), order["sale_order_id"].ToString(), order["reference_order_number"].ToString());
                     if (respuestaiEnvios == null)
                     {
                        log.EscribeLog("Error al consultar estatus iEnvios.");
                        log.EscribeLog("Pedido: " + order["reference_order_number"]);
                        log.EscribeLog("Guia: " + order["tracking_number"]);
                     }
                     else
                     {
                        if (respuestaiEnvios.error == false)
                        {
                           ValidaEntregado(new []{ "Entregada" }, respuestaiEnvios.data.estatus, order["reference_order_number"].ToString());
                           log.EscribeLog("Pedido: " + order["reference_order_number"]);
                           log.EscribeLog("Estatus anterior: " + order["shipping_status"]);
                           log.EscribeLog("Estatus nuevo: " + respuestaiEnvios.data.estatus);
                           log.EscribeLog("Guia: " + order["tracking_number"]);
                           cotizaciones.UpdMerchantOrderHeader("carrier_shipping_status='" + respuestaiEnvios.data.estatus + "', carrier_date_tracking='" +DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'", "reference_order_number='" + order["reference_order_number"] + "'");
                           cotizaciones.AddSaleOrderTrackingHistory(order["sale_order_id"].ToString(), order["carrier_name"].ToString(), order["tracking_number"].ToString(), respuestaiEnvios.data.estatus,DateTime.Now);
                        }
                        else
                        {
                           log.EscribeLog("Error al consultar estatus iEnvios.");
                           log.EscribeLog("Pedido: " + order["reference_order_number"]);
                           log.EscribeLog("Guia: " + order["tracking_number"]);
                        }
                     }
                     #endregion
                     break;
               }
            }
         }
         catch (FaultException fex)
         {
            log.EscribeLog("Error: " + fex.Message + " " + fex.Reason + " " + fex.StackTrace);
         }
         catch (WebException wex)
         {
            log.EscribeLog("Error: " + wex.Message + " " + wex.Response);
         }
         catch (Exception ex)
         {
            log.EscribeLog("Error: " + ex.Message + " " + ex.StackTrace);
         }
      }

      private static void ValidaEntregado(string[] estatuscompletados, string estatus, string pedido)
      {
         if (estatuscompletados.Any(e => e == estatus))
         {
            if (string.Compare(ConfigurationManager.AppSettings["Plataforma"], "EK", StringComparison.CurrentCultureIgnoreCase) == 0)
            {
               var modeloelektra = new mdlElektra();
               modeloelektra.Login();
               modeloelektra.ConfirmDelivered(pedido);
            }
            var cotizaciones = new Cotizaciones();
            cotizaciones.UpdMerchantOrderHeader("shipping_status='delivered'", "reference_order_number='" + pedido + "'");
         }
      }
   }
}
