using AppData;
using SteamWare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI;

namespace NKC_WF
{
    public partial class OrderManager : BasePage
    {
        #region Protected Fields

        /// <summary>
        /// Folder REMOTA x copia verso SQL
        /// </summary>
        protected string _SqlCopyDir = memLayer.ML.CRS("_SqlCopyDir");

        /// <summary>
        /// Folder x SQL import
        /// </summary>
        protected string _SqlImportDir = memLayer.ML.CRS("_SqlImportDir");

        /// <summary>
        /// Path base x nesting
        /// </summary>
        protected string cadBasePath = $"{memLayer.ML.CRS("nestBasePath")}{memLayer.ML.CRS("drawingFolder")}/";

        /// <summary>
        /// Path base x server
        /// </summary>
        protected string srvCadBasePath = $"{memLayer.ML.CRS("servBasePath")}{memLayer.ML.CRS("drawingFolder")}/";

        #endregion Protected Fields

        #region Private Methods

        private void Cmp_batchList_eh_doRefresh(object sender, EventArgs e)
        {
            doUpdate();
        }

        private void Cmp_fileUpload_eh_doRefresh(object sender, EventArgs e)
        {
            doUpdate();
        }

        /// <summary>
        /// Ora continuo processing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cmp_fileUpload_eh_FileUploaded(object sender, WebUserContols.FileUploadEventArgs e)
        {
            /*--------------------------------------------
             * Note validazione:
             * - leggo cSV
             * - carico su DB
             * - verifico (come ora x DXF) TUTTI i particolari
             * - cerco su tab ItemValidation
             *   --> NON TROVATO --> creo record IV + record Batch stato 8, con KitID = OrdID = 0, DA VALUTARE!!!
             *    - se valutazione tempo <= 1 sec --> NON VALIDO
             *    - se valutazione tempo > 1 sec --> VALIDO
             *
             *   --> trovato
             *    - se valido --> check DXF,
             *      --> dxf ok --> finito
             *      --> dxf non trovato --> NON VALIDO, segnalo errore su part
             *    - se NON valido --> segnalo errore su part
             *
             *--------------------------------------------*/

            bool dataValidated = true;
            DateTime adesso = DateTime.Now;
            string dirFrom = e.LocalPath;
            string dirTo = $"{_SqlCopyDir}{adesso.ToString("yyyy-MM")}\\";
            string dirImport = $"{_SqlImportDir}{adesso.ToString("yyyy-MM")}\\";
            int batchID = 0;
            // recupero elenco parti validate...
            DS_App.ItemListDataTable ItemValitadion = DLMan.taIL.GetData();
            // preporcessing file: leggo e correggo:
            // - sostituisco "," --> ";" come separatore
            // - tolgo "" e spazi da stringa
            string[] rawLines = System.IO.File.ReadAllLines($"{e.LocalPath}{e.FileName}");
            string[] fixLines = new string[rawLines.Length];
            int numRow = 0;
            if (memLayer.ML.CRB("preFixCsv"))
            {
                foreach (var riga in rawLines)
                {
                    string newLine = "";
                    // splitto con "
                    string[] rowPart = riga.Split('"');
                    int i = 0;
                    foreach (var parte in rowPart)
                    {
                        if (i % 2 == 0)
                        {
                            // pari --> sostituisco , --> ;
                            newLine += parte.Replace(",", ";");
                        }
                        else
                        {
                            // dispari: trimmo
                            newLine += parte.Trim();
                        }
                        i++;
                    }
                    // ricombino!
                    fixLines[numRow] = newLine;
                    numRow++;
                }
                // salvo NUOVO file...
                System.IO.File.WriteAllLines($"{e.LocalPath}{e.FileName}", fixLines);
            }
            // copio su server SQL
            try
            {
                // copio su SQL...
                fileMover.obj.copiaFile(dirFrom, dirTo, e.FileName);
            }
            catch (Exception exc)
            {
                logger.lg.scriviLog($"{traduci("ErrOrderCsvImp01")}:{Environment.NewLine}{exc}");
                DLMan.taEL.insertQuery(DateTime.Now, "Copy CSV", $"{e.BatchName}", $"{e.BatchName}.{e.FileName}", $"Exception: {exc}");
            }
            // chiamo stored caricamento
            DS_App.ImportLogDataTable tabDati = null;
            try
            {
                // pulizia eventuali vecchi file errore in "dirTo"
                string[] file2del = Directory.GetFiles(dirTo, "error*");
                if (file2del.Length > 0)
                {
                    logger.lg.scriviLog($"Trovati {file2del.Length} file errore, li elimino");
                    foreach (var item in file2del)
                    {
                        File.Delete(item);
                        logger.lg.scriviLog($"Eliminato {item}");
                    }
                }

                // chiamo procedura SQL x import...
                tabDati = DLMan.taImpLog.importCsvOrd($"{dirImport}", e.FileName, e.BatchName, ";", "\n", "2", 0, 0, 0);
            }
            catch (Exception exc)
            {
                logger.lg.scriviLog($"{traduci("ErrOrderCsvImp02")}:{Environment.NewLine}{exc}");
                // salvo log errore...
                DLMan.taEL.insertQuery(DateTime.Now, "Upload CSV", $"{e.BatchName}", $"{e.BatchName}.{e.FileName}", $"Exception: {exc}");
                dataValidated = false;
            }
            // FIX eventuali cadFilePath...
            DLMan.taIL.updateCadPath(cadBasePath, 0, false);
            // recupero da batch la riga impostata...
            try
            {
                var tabBatch = DLMan.taBL.getLastByTakt(e.BatchName);
                if (tabBatch != null)
                {
                    if (tabBatch.Count > 0)
                    {
                        batchID = tabBatch[0].BatchID;
                    }
                }
            }
            catch (Exception exc)
            {
                logger.lg.scriviLog($"{traduci("ErrOrderCsvImp03")}:{Environment.NewLine}{exc}");
                dataValidated = false;
            }
            if (dataValidated && batchID > 0)
            {
                dataValidated = doValidations(batchID);
            }
            if (!dataValidated)
            {
                try
                {
                    var newBatch = tabDati[0];
                    int bStatus = 7;
                    DLMan.taBL.updateStatus(batchID, bStatus, e.BatchName, -1);
                }
                catch
                { }
            }
            Response.Redirect(Request.RawUrl);
            //doUpdate();
        }

        /// <summary>
        /// Effettua validazione dati
        /// </summary>
        private bool doValidations(int batchID)
        {
            bool allOk = true;
            List<string> missingDxfList = new List<string>();
            // faccio un ciclo su OGNI record Part --> cerco se mancassero dei file dxf...
            try
            {
                var tabParts = DLMan.taIL.getByBatch(batchID);
                if (tabParts.Count > 0)
                {
                    bool fileOk = false;
                    string localPath = "";
                    foreach (var item in tabParts)
                    {
                        // verifico SE già processato...
                        if (!missingDxfList.Contains(item.ItemExtCode))
                        {
                            // cerco file! sostituisco cadBasePath --> srvCadBasePath
                            if (string.IsNullOrEmpty(item.CadFilePath))
                            {
                                localPath = $"{srvCadBasePath}{item.ItemExtCode}.dxf";
                            }
                            else
                            {
                                localPath = item.CadFilePath.Replace(cadBasePath, srvCadBasePath);
                            }
                            // fix slash/backslash
                            localPath = localPath.Replace("/", "\\");
                            // verifico
                            fileOk = File.Exists(localPath);
                            if (!fileOk)
                            {
                                string errMsg = $"{traduci("ErrOrderDxfNotFound")} {localPath} | part {item.ItemExtCode} | {item.ItemDesc}";
                                DLMan.taEL.insertQuery(DateTime.Now, "I.1", $"B.{batchID}", $"{item.ItemExtCode}.dxf", errMsg);
                                allOk = false;
                                missingDxfList.Add(item.ItemExtCode);
                                logger.lg.scriviLog(errMsg);
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                allOk = false;
                string errMsg = $"Excetion on doValidations fot BatchId: {batchID}{Environment.NewLine}{exc}";
                logger.lg.scriviLog(errMsg);
                DLMan.taEL.insertQuery(DateTime.Now, "I.2", $"B.{batchID}", "doValidations", errMsg);
            }
            // risultato
            return allOk;
        }

        #endregion Private Methods

        #region Protected Methods

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ((SiteMaster)this.Master).showSearch = false;
                doUpdate();
            }
            cmp_batchList.eh_doRefresh += Cmp_batchList_eh_doRefresh;
            cmp_fileUpload.eh_doRefresh += Cmp_fileUpload_eh_doRefresh;
            cmp_fileUpload.eh_FileUploaded += Cmp_fileUpload_eh_FileUploaded;
        }

        #endregion Protected Methods

        #region Public Methods

        /// <summary>
        /// Update interfaccia
        /// </summary>
        public void doUpdate()
        {
            cmp_batchList.doUpdate();
        }

        #endregion Public Methods
    }
}