using AppData;
using SteamWare;
using System;

namespace NKC_WF.WebUserControls
{
    public partial class cmp_kitImpCheck : BaseUserControl
    {
        /// <summary>
        /// Folder x SQL import
        /// </summary>
        protected string _SqlImportDir = memLayer.ML.CRS("_SqlImportDir");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                displayMessage("", false);
            }
        }
        /// <summary>
        /// Nome file caricato
        /// </summary>
        public string fileName
        {
            get
            {
                return hfFileName.Value;
            }
            set
            {
                hfFileName.Value = value;
            }
        }
        /// <summary>
        /// Nome file caricato
        /// </summary>
        public string batchName
        {
            get
            {
                return hfBatchName.Value;
            }
            set
            {
                hfBatchName.Value = value;
            }
        }
        /// <summary>
        /// NUM TASK eseguito
        /// </summary>
        public int numTask
        {
            get
            {
                int answ = 0;
                int.TryParse(hfNumTask.Value, out answ);
                return answ;
            }
            set
            {
                hfNumTask.Value = value.ToString();
            }
        }
        /// <summary>
        /// Esito OK a check import
        /// </summary>
        public bool checkOk
        {
            get
            {
                bool answ = false;
                bool.TryParse(hfCheckOk.Value, out answ);
                return answ;
            }
            set
            {
                hfCheckOk.Value = value.ToString();
            }
        }
        /// <summary>
        /// File effettivamente caricato
        /// </summary>
        public bool imported
        {
            get
            {
                bool answ = false;
                bool.TryParse(hfImported.Value, out answ);
                return answ;
            }
            set
            {
                hfImported.Value = value.ToString();
            }
        }
        /// <summary>
        /// Verifico il file e aggiorno visualizazione di conseguenza
        /// </summary>
        private void processValidation()
        {
            // controllo ed aggiorno...
            bool fileOk = !string.IsNullOrEmpty(fileName);

            string newClass1 = fileOk ? "alert alert-success" : "alert alert-secondary";
            string newClass2 = checkOk ? "alert alert-success" : "alert alert-secondary";
            string newClass3 = imported ? "alert alert-success" : "alert alert-secondary";
            updateClass(divStep1, newClass1);
            updateClass(divStep2, newClass2);
            updateClass(divStep3, newClass3);
        }

        private static void updateClass(System.Web.UI.HtmlControls.HtmlGenericControl currControl, string newClass)
        {
            currControl.Attributes.Remove("class");
            currControl.Attributes.Add("class", newClass);
            currControl.DataBind();
        }


        /// <summary>
        /// Effettua un test di importazione o l'importazione effettiva
        /// </summary>
        /// <param name="testOnly">true= solo test, false= vero import (SE non ci sono errori)</param>
        public void tryImport(bool testOnly)
        {
            DateTime adesso = DateTime.Now;
            string dirImport = $"{_SqlImportDir}{adesso.ToString("yyyy-MM")}\\";
            try
            {
                // chiamo procedura SQL x import BATCH... come test o reale secondo del parametro
                var tabCount = DLMan.taCount.getNextNum("NumTicket");
                if (tabCount.Count == 1)
                {
                    numTask = tabCount[0].LastNum;
                }
                var risultati = DLMan.taImpLog.importCsvKit($"{dirImport}", fileName, batchName, ";", "\n", "2", numTask, 0, 0, testOnly);
                // se ho delle righe di log processo...
                bool allCheck = true;
                foreach (var item in risultati)
                {
                    if (!item.IsOk)
                    {
                        allCheck = false;
                    }
                }
                checkOk = allCheck;
                // ho importato SOLO SE era stato richiesto e se NON HO avuto errori
                imported = checkOk && !testOnly;
                // ora effettua validazione e mostra eventuale esito...
                processValidation();
                displayMessage($"{traduci("KitDataImportExecuted")}: {traduci("Validated")}: {checkOk} | {traduci("Imported")} : {imported}", false);
            }
            catch (Exception exc)
            {
                string fullMessage = $"{traduci("KitDataImportException")}:{Environment.NewLine}{exc}";
                logger.lg.scriviLog(fullMessage);
                displayMessage(fullMessage, true);
            }
        }

        protected void lbtDoAction_Click(object sender, EventArgs e)
        {
            // in base a cosa ho in memoria procedo con successivo step
            if (!checkOk || !imported)
            {
                tryImport(false);
            }
            processValidation();
            if (imported)
            {
                raiseReset();
            }
        }
        /// <summary>
        /// Display message + gest visualizzazione
        /// </summary>
        /// <param name="mainMessage"></param>
        /// <param name="showFull"></param>
        protected void displayMessage(string mainMessage, bool showFull)
        {
            lblOutTask.Text = mainMessage;
            lblOutTask.ToolTip = mainMessage;

            hlShowErrors.Visible = showFull;
            if (showFull)
            {
                hlShowErrors.NavigateUrl = $"../site/ErrorsLog?PUID={batchName}.{numTask}";
            }
        }
    }
}