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

namespace NKC_WF
{
    public partial class OrderManager : BasePage
    {
        /// <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")}/";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                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;
        }
        /// <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 = DataLayer.man.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($"Eccezione in Copia SQL file:{Environment.NewLine}{exc}");
                DataLayer.man.taEL.insertQuery(DateTime.Now, "Copy CSV", $"{e.BatchName}", $"{e.BatchName}.{e.FileName}", $"Exception: {exc}");
            }
            // chiamo stored caricamento
            DS_App.ImportLogDataTable tabDati = null;
            try
            {
                // chiamo procedura SQL x import... 
                tabDati = DataLayer.man.taImpLog.importCsvOrd($"{dirImport}", e.FileName, e.BatchName, ";", "\n", "2", 0, 0, 0);
            }
            catch (Exception exc)
            {
                logger.lg.scriviLog($"Eccezione in IMPORT file:{Environment.NewLine}{exc}");
                // salvo log errore...
                DataLayer.man.taEL.insertQuery(DateTime.Now, "Upload CSV", $"{e.BatchName}", $"{e.BatchName}.{e.FileName}", $"Exception: {exc}");
                dataValidated = false;
            }
            // FIX eventuali cadFilePath...
            DataLayer.man.taIL.updateCadPath(cadBasePath, 0, false);
            // recupero da batch la riga impostata...
            try
            {
                var tabBatch = DataLayer.man.taBL.getLastByTakt(e.BatchName);
                if (tabBatch != null)
                {
                    if (tabBatch.Count > 0)
                    {
                        batchID = tabBatch[0].BatchID;
                    }
                }
            }
            catch (Exception exc)
            {
                logger.lg.scriviLog($"Eccezione in verifica file:{Environment.NewLine}{exc}");
                dataValidated = false;
            }
            if (dataValidated && batchID > 0)
            {
                dataValidated = doValidations(batchID);
            }
            if (!dataValidated)
            {
                try
                {
                    var newBatch = tabDati[0];
                    int bStatus = 7;
                    DataLayer.man.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 = DataLayer.man.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);
                            }
                            // verifico
                            fileOk = System.IO.File.Exists(localPath);
                            if (!fileOk)
                            {
                                DataLayer.man.taEL.insertQuery(DateTime.Now, "I.1", $"B.{batchID}", $"{item.ItemExtCode}.dxf", $"DXF File not found {localPath} | part {item.ItemExtCode} | {item.ItemDesc}");
                                allOk = false;
                                missingDxfList.Add(item.ItemExtCode);
                            }
                        }
                    }
                }
            }
            catch
            { }
            // cerco errori preesistenti
            return allOk;
        }

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

        private void Cmp_batchList_eh_doRefresh(object sender, EventArgs e)
        {
            doUpdate();
        }
        /// <summary>
        /// Update interfaccia
        /// </summary>
        public void doUpdate()
        {
            cmp_batchList.doUpdate();
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            doUpdate();
        }
    }
}