using ProcessShipperMiddleWare.Models;
using SmartLincInterface;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ProcessShipperMiddleWare
{
    public class SelectInterface
    {
        DatabaseHelper databaseHelper = null;
        OrderDetailsResult orderDetailsResult = new OrderDetailsResult();

        public SelectInterface()
        {
            databaseHelper = new DatabaseHelper();
        }
        public EntityShipment Pull(EntityShipment objES)
        {

            if (!string.IsNullOrEmpty(objES.strDeliveryDocNumber)
                        && objES.ToolKit.ID != null
                        && objES.ToolKit.ID.ToLower() == "select")
            {
                orderDetailsResult = databaseHelper.GetOrderDetails(objES.strDeliveryDocNumber);
            }


            EntityShipment entityShipment = new EntityShipment();
            entityShipment.lstShipTo = new List<EntityAddress>();
            entityShipment.lstContainer = new List<EntityContainer>();
            entityShipment.objShipMethod = new EntityShipMethod();
            entityShipment.objDetails = new EntityShipmentDetails();
            entityShipment.ToolKit = new EntityToolKit();
            entityShipment.lstEntityResponseStatus = new List<EntityResponseStatus>();
            entityShipment.ToolKit.DocumentType = eDocumentType.Invoice;

            try
            {
                entityShipment.lstEntityResponseStatus.Add(FillStatus("SELECT Pull Method Called", ResponseStatusType.LOG));

                // Set payment terms                
                string payorTerms = "SENDER";
                string payorAcct = "251144621";
                entityShipment.objShipMethod = new EntityShipMethod();
                entityShipment.objShipMethod.strShipViaCode = "123456";
                entityShipment.objShipMethod.strPaymentTerms = payorTerms;
                entityShipment.objShipMethod.strPayorAccountNumber = payorAcct;
                entityShipment.objShipMethod.PaymentTermType = ePaymentTerms.ThirdParty;

                // Set CarrierType  
                entityShipment.CarrierType = eCarrierType.UPS;
                entityShipment.UPSServiceCodes = eUPSServiceCodes.UPS_Ground;



                // Set shipment details
                entityShipment.objDetails.strInvoiceNumber = objES.objDetails.strDeliveryDocNumber;
                entityShipment.objDetails.strPONumber =orderDetailsResult.PURCHASE_ORDER_NUMBER;
                entityShipment.objDetails.strShippingInstructions = orderDetailsResult.DESCRIPTION;
                entityShipment.objDetails.strDeliveryDocNumber = objES.objDetails.strDeliveryDocNumber;
                entityShipment.dtShipDate = DateTime.Now;

                // Create ShipTo address
                EntityAddress shipToAddress = new EntityAddress();
                shipToAddress.strCustomerID = "SEL-CUST-001";
                shipToAddress.strCompanyName = orderDetailsResult.ORGANIZATION;
                shipToAddress.strContactName = orderDetailsResult.NAME;
                shipToAddress.strAddressLine1 = orderDetailsResult.LABEL_LINE_1;
                shipToAddress.strAddressLine2 = orderDetailsResult.LABEL_LINE_2;
                shipToAddress.strAddressLine3 =
                        orderDetailsResult.LABEL_LINE_3 + " " +
                        orderDetailsResult.LABEL_LINE_4 + " " +
                        orderDetailsResult.LABEL_LINE_5 + " " +
                        orderDetailsResult.LABEL_LINE_6 + " " +
                        orderDetailsResult.LABEL_LINE_7;
                shipToAddress.strCity = orderDetailsResult.CITY;
                shipToAddress.strState = orderDetailsResult.STATE;
                shipToAddress.strPostalCode = orderDetailsResult.ZIP;
                shipToAddress.strCountryCode = orderDetailsResult.COUNTRY; ;
                shipToAddress.strPhoneNumber = orderDetailsResult.PHONE;
                shipToAddress.strFaxNumber = orderDetailsResult.FAX;
                shipToAddress.strEmailAddress = "roshni.nandawani@kwglobal.com"; //orderDetailsResult.EMAIL;
                entityShipment.objShipTo = shipToAddress;
                entityShipment.lstShipTo.Add(shipToAddress);

                // Create BillTo address
                EntityAddress billToAddress = new EntityAddress();
                billToAddress.strCustomerID = "SEL-BILL-001";
                billToAddress.strAccountNumber = "ACC-SELECT-001";
                billToAddress.strCompanyName = orderDetailsResult.ORGANIZATION;
                billToAddress.strContactName = orderDetailsResult.NAME;
                billToAddress.strAddressLine1 = orderDetailsResult.LABEL_LINE_1;
                billToAddress.strAddressLine2 = orderDetailsResult.LABEL_LINE_2;
                billToAddress.strAddressLine3 =
                        orderDetailsResult.LABEL_LINE_3 + " " +
                        orderDetailsResult.LABEL_LINE_4 + " " +
                        orderDetailsResult.LABEL_LINE_5 + " " +
                        orderDetailsResult.LABEL_LINE_6 + " " +
                        orderDetailsResult.LABEL_LINE_7;
                billToAddress.strCity = orderDetailsResult.CITY;
                billToAddress.strState = orderDetailsResult.STATE;
                billToAddress.strPostalCode = orderDetailsResult.ZIP;
                billToAddress.strCountryCode = orderDetailsResult.COUNTRY; ;
                billToAddress.strPhoneNumber = orderDetailsResult.PHONE;
                billToAddress.strFaxNumber = orderDetailsResult.FAX;
                billToAddress.strEmailAddress =orderDetailsResult.EMAIL;
                entityShipment.objBillTo = billToAddress;

                // Create ShipFrom address
              /*  EntityAddress shipFromAddress = new EntityAddress();
                shipFromAddress.strCompanyName = "SELECT Warehouse";
                shipFromAddress.strContactName = "Bob SELECT";
                shipFromAddress.strAddressLine1 = "789 SELECT Warehouse Blvd";
                shipFromAddress.strAddressLine2 = "Dock 3";
                shipFromAddress.strAddressLine3 = "Bay 12";
                shipFromAddress.strCity = "SELECT Warehouse City";
                shipFromAddress.strState = "TX";
                shipFromAddress.strPostalCode = "75001";
                shipFromAddress.strCountryCode = "US";
                shipFromAddress.strPhoneNumber = "555-WARE-SEL";
                shipFromAddress.strFaxNumber = "555-WARE-FAX";
                shipFromAddress.strEmailAddress = "warehouse@select.com";
                entityShipment.objShipFrom = shipFromAddress;*/

            

                EntityPackageGroup packageGroup = new EntityPackageGroup();
                packageGroup.lstLineItem = new List<EntityLineItem>();


                List<OrderItemResult> orderItemResult =
                       databaseHelper.GetOrderItems(objES.objDetails.strDeliveryDocNumber);


                // Create package groups
                int maxRecords = 50;
                if (orderItemResult != null && orderItemResult.Count > 0)
                {
                    int i = 0;
                    foreach (var line in orderItemResult.Take(maxRecords))
                    {
                        i = i + 1;
                        EntityLineItem lineItem = new EntityLineItem();
                        //lineItem.strItemNumber = string.IsNullOrWhiteSpace(line.order_address_id)
                        //        ? "UNKNOWN"
                        //        : line.order_address_id.Trim();
                        lineItem.strItemNumber = (i).ToString();
                        string bookTitle = string.IsNullOrWhiteSpace(line.BookTitle)
                                   ? "Book"
                                   : line.BookTitle.Trim();
                        string isbn = string.IsNullOrWhiteSpace(line.ISBN)
                            ? ""
                            : line.ISBN.Trim();
                        lineItem.strItemDescription = bookTitle +
                            (string.IsNullOrEmpty(isbn) ? "" : " - " + isbn);
                        int qty = 1;
                        if (!string.IsNullOrEmpty(line.Quantity))
                        {
                            int.TryParse(line.Quantity, out qty);
                            if (qty <= 0) qty = 1;
                        }
                        lineItem.intOrderedQuantity = qty;
                       
                        packageGroup.lstLineItem.Add(lineItem);
                    }
                }
                EntityContainer container = new EntityContainer();
                container.lstPackageGroup = new List<EntityPackageGroup>();
                container.lstPackageGroup.Add(packageGroup);
               
                container.objPackageWeight = new PackageWeight();                
                container.strAlternatePackageID = "12345";

              


                entityShipment.lstContainer = new List<EntityContainer>();
                entityShipment.lstContainer.Add(container);


                entityShipment.lstEntityResponseStatus.Add(FillStatus("SELECT Pull completed successfully", ResponseStatusType.LOG));
            }
            catch (Exception ex)
            {
                entityShipment.lstEntityResponseStatus.Add(FillStatus(ex.Message, ResponseStatusType.ERROR));
            }

            entityShipment.PackingOn = true;

           
            return entityShipment;
        }

        public EntityShipment Putback(EntityShipment objES)
        {
            objES.lstEntityResponseStatus = new List<EntityResponseStatus>();
            objES.lstEntityResponseStatus.Add(FillStatus("SELECT Putback Method Called", ResponseStatusType.LOG));

            try
            {
                foreach (EntityContainer container in objES.lstContainer)
                {
                    objES.lstEntityResponseStatus.Add(FillStatus($"Processing container: {container.strAlternatePackageID}", ResponseStatusType.LOG));
                }
                objES.lstEntityResponseStatus.Add(FillStatus("SELECT Putback completed successfully", ResponseStatusType.LOG));
            }
            catch (Exception ex)
            {
                objES.lstEntityResponseStatus.Add(FillStatus(ex.Message, ResponseStatusType.ERROR));
            }

            return objES;
        }

        public EntityShipment Void(EntityShipment objES)
        {
            objES.lstEntityResponseStatus = new List<EntityResponseStatus>();
            objES.lstEntityResponseStatus.Add(FillStatus("SELECT Void Method Called", ResponseStatusType.LOG));

            try
            {
                objES.lstEntityResponseStatus.Add(FillStatus($"Voiding shipment: {objES.objDetails.strDeliveryDocNumber}", ResponseStatusType.LOG));
                objES.lstEntityResponseStatus.Add(FillStatus("SELECT Void completed successfully", ResponseStatusType.LOG));
            }
            catch (Exception ex)
            {
                objES.lstEntityResponseStatus.Add(FillStatus(ex.Message, ResponseStatusType.ERROR));
            }

            return objES;
        }

        private EntityResponseStatus FillStatus(string strMessage, ResponseStatusType eStatusType)
        {
            EntityResponseStatus entityResponseStatus = new EntityResponseStatus();
            entityResponseStatus.Message = strMessage;
            entityResponseStatus.StatusType = eStatusType;

            // Logging disabled for SELECT interface

            return entityResponseStatus;
        }
    }
}