using System;
using System.IO;
using System.Collections.Generic;
using uri_import.EClasses;
using uri_import.FClasses;
using uri_import.AClasses;
using uri_import.PClasses;
using Acumatica.Default_20_200_001.Model;
using Acumatica.Manufacturing_21_200_001.Model;
using Acumatica.RESTClient.Model;

namespace uri_import
{
    class Program
    {
        public static Common Cmn { get; set; }
        static void Main(string[] args)
        {
            Cmn = JSONActions.ReadSettings("settings.json");
            FileActions.MakeDirectories();
            Ex365 exch = new Ex365(Cmn.Email.Username,
                Cmn.Email.Password,
                Cmn.Email.Url,
                (Independentsoft.Exchange.StandardFolder)Cmn.Email.Mailbox);
            List<EmailAttachment> pos = exch.GetPOs(Cmn.Email.Filter);
            List<SalesOrder> sos = new List<SalesOrder>();
            WritePOsToDirectory(pos);
            try
            {
                var config = AcumaticaREST.Config(Cmn.Acumatica.Url,
                    Cmn.Acumatica.Username,
                    Cmn.Acumatica.Password,
                    Cmn.Acumatica.Tenant,
                    null,
                    null);

                foreach (EmailAttachment ea in pos)
                {
                    try
                    {
                        List<string> lines = PDFHelper.PDFLinesToText(ea.FilePath);
                    }
                    catch (Exception lex)
                    {
                        ea.Errors.Add(string.Format("{0} {1} {2}",
                            DateTime.Now.ToShortDateString(),
                            DateTime.Now.ToShortTimeString(),
                            lex.Message));
                    }
                    ea.SalesOrder = PDFHelper.PDFBuildSalesOrder(PDFHelper.PDFLinesToText(ea.FilePath));
                    SalesOrder order = ea.SalesOrder;

                    foreach (SalesOrderDetail detail in order.Details)
                    {
                        Dictionary<string, CustomField> inner = new Dictionary<string, CustomField>();
                        CustomBooleanField b = new CustomBooleanField(true, "CustomBooleanField");
                        inner.Add("AMProdCreate", b);
                        detail.Custom = new Dictionary<string, Dictionary<string, CustomField>>();
                        detail.Custom.Add("Transactions", inner);

                    }
                    AcumaticaREST.CreateSalesOrder(ref order, config, ea.FileName, ea.Content);
                    ea.SalesOrder.OrderNbr = order.OrderNbr;
                    ea.SalesOrder.ID = order.ID;
                    int ln = 1;
                    foreach (SalesOrderDetail detail in ea.SalesOrder.Details)
                    {
                        ProductionOrder prod = new ProductionOrder();
                        prod.OrderType = "RO";
                        prod.QtytoProduce = detail.OrderQty;
                        prod.InventoryID = detail.InventoryID;
                        prod.SOOrderNbr = order.OrderNbr;
                        prod.SOOrderType = "SO";
                        prod.SOLineNbr = detail.LineNbr;
                        ln = ln + 1;
                        AcumaticaREST.CreateProductionOrder(config,
                            ref prod,
                            Cmn.Acumatica.Url,
                            Cmn.Acumatica.Username,
                            Cmn.Acumatica.Password,
                            Cmn.Acumatica.Tenant,
                            null,
                            null);
                        ea.ProductionOrders.Add(prod);
                    }
                }
                foreach (EmailAttachment ea in pos)
                {
                    AcumaticaREST.ReleaseAndLinkProductionOrders(config,
                        ea,
                        Cmn.Acumatica.Url,
                        Cmn.Acumatica.Username,
                        Cmn.Acumatica.Password,
                        Cmn.Acumatica.Tenant,
                        null,
                        null);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                AcumaticaREST.APILogout(Cmn.Acumatica.Url,
                    Cmn.Acumatica.Username,
                    Cmn.Acumatica.Password,
                    Cmn.Acumatica.Tenant,
                    null,
                    null);
            }
            using (RestService service = new RestService(Cmn.Acumatica.Url,
                Cmn.Acumatica.Username,
                Cmn.Acumatica.Password,
                Cmn.Acumatica.Tenant,
                Cmn.Acumatica.Locale))
            {
                foreach (EmailAttachment ea in pos)
                {
                    try
                    {
                        AcumaticaREST.PutFile(service,
                            ea.SalesOrder,
                            Cmn.Acumatica.Url,
                            "SO",
                            ea.SalesOrder.OrderNbr.Value.ToString(),
                            ea.FileName,
                            ea.Content);
                    }
                    catch { }
                }
            }

        }
        static void WritePOsToDirectory(List<EmailAttachment> pos)
        {
            foreach (EmailAttachment obj in pos)
            {
                string path = Path.Combine(FileActions.Attachments,
                    obj.FileName);
                if (!File.Exists(path))
                    File.WriteAllBytes(path,
                        obj.Content);
                Console.WriteLine(obj.FilePath);
            }
        }
    }
}
