using AppData;
using NKC_SDK;
using NKC_WF.Controllers;
using Newtonsoft.Json;
using SteamWare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;

namespace NKC_WF.WebUserControls
{
    public partial class cmp_secScreen : BaseUserControl
    {
        /// <summary>
        /// Codice macchina (HARD CODED x ora)
        /// </summary>
        protected string machine = "WRK001";

        public int countDown
        {
            get
            {
                int answ = 0;
                int.TryParse(hfCountDown.Value, out answ);
                return answ;
            }
            set
            {
                hfCountDown.Value = value.ToString();
            }
        }

        public int currNum
        {
            get
            {
                int answ = 0;
                int.TryParse(hfNum.Value, out answ);
                return answ;
            }
            set
            {
                hfNum.Value = $"{value:000000}";
            }
        }

        public string itemCode
        {
            get
            {
                return hfItemCode.Value;
            }
            set
            {
                hfItemCode.Value = value;
            }
        }

        public string itemDtmx
        {
            get
            {
                return hfItemDtmx.Value;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    cmp_ItemDet.Visible = true;
                    lblMessage.Visible = false;
                    hlPdfOpener.Enabled = true;
                    hlPdfOpener.CssClass = "btn btn-success btn-block";
                    hfItemDtmx.Value = value;
                    // cerco e salvo!
                    var tabItem = DLMan.taIL.getBySearch(0, value, 0, 9999);
                    if (tabItem != null && tabItem.Count > 0)
                    {
                        int ItemId = tabItem[0].ItemID;
                        cmp_ItemDet.ItemId = ItemId;
                        itemCode = tabItem[0].ItemExtCode;
                        pdfPath = tabItem[0].PdfFilePath.ToLower();
                    }
                }
                else
                {
                    cmp_ItemDet.Visible = false;
                    lblMessage.Visible = true;
                    hlPdfOpener.Enabled = false;
                    hlPdfOpener.CssClass = "btn btn-outline-light text-light btn-block";
                    hfItemDtmx.Value = "";
                }
            }
        }

        public string newDtmx
        {
            get
            {
                string answ = ComLib.getSecScreenRequest(codSSC);
                answ = string.IsNullOrEmpty(answ) ? "" : answ;
                return answ;
            }
        }

        public string pdfPath
        {
            get
            {
                return hfItemPdf.Value;
            }
            set
            {
                // check preliminare: deve essere un file ".pdf..."
                if (value.ToLower().Trim().EndsWith(".pdf"))
                {
                    // poiché è necessario copiare in locale il pdf...
                    string nameOnly = $"~/temp/{itemCode}.pdf";
                    hfItemPdf.Value = nameOnly;
                    // svuoto files vecchi...
                    removeOldTemp();

                    // faccio verifica SE sia necessario fare sostituzioni
                    string rawData = memLayer.ML.cdv("pdfPathSanitizer");
                    if (!string.IsNullOrEmpty(rawData))
                    {
                        string[] listaSubst = null;
                        try
                        {
                            listaSubst = rawData.Split('|');
                        }
                        catch
                        { }
                        // se trovato..
                        if (listaSubst != null && listaSubst.Length > 0)
                        {
                            for (int i = 0; i < listaSubst.Length / 2; i++)
                            {
                                value = value.Replace(listaSubst[i], listaSubst[i + 1]);
                            }
                        }
                    }
                    try
                    {
                        // loggo che sto x copiare
                        logger.lg.scriviLog($"Requested copy from {value.Trim()} --> {Server.MapPath(nameOnly)}");
                        // copio in locale file...
                        File.Copy(value.Trim(), Server.MapPath(nameOnly));
                    }
                    catch (Exception exc)
                    {
                        string fullMessage = $"SecScreed: Exception on setPdfPath:{Environment.NewLine}{exc}";
                        logger.lg.scriviLog(fullMessage);
                    }
                    // update...
                    hlPdfOpener.NavigateUrl = nameOnly;
                }
                else
                {
                    string fullMessage = $"SecScreed: Error on pdfPath set value: [{value}]";
                    logger.lg.scriviLog(fullMessage);
                }
            }
        }

        public int SheetId
        {
            get
            {
                int answ = 0;
                int.TryParse(hfSheetId.Value, out answ);
                return answ;
            }
            set
            {
                hfSheetId.Value = $"{value}";
                hlShowCurrSheet.NavigateUrl = $"~/site/SvgFull?sheetId={value}";
            }
        }

        protected string codSSC
        {
            get
            {
                return $"SSC{currNum:000000}";
            }
        }

        /// <summary>
        /// Aggiorna componente principale e child components
        /// </summary>
        public void doUpdate()
        {
            // valutato ma non usato pdf.js:
            // https://mozilla.github.io/pdf.js/examples/index.html#interactive-examples

            // se è variato da current...
            if (newDtmx != itemDtmx)
            {
                itemDtmx = newDtmx;
            }
        }

        /// <summary>
        /// restituisce URL immagine QRCode
        /// </summary>
        /// <returns></returns>
        public string getImageUrl()
        {
            string baseUrl = $"{memLayer.ML.CRS("matrixUrl")}/HOME/QR_site/JSON?val=";
            string payload = "{'baseUrl':'{0}','parameters':['" + codSSC + "']}";
            string answ = $"{baseUrl}{payload}";
            return answ;
        }

        public void refreshCodPost()
        {
            // se NON HO PIU' un codice valido nella richiesta redis
            if (string.IsNullOrEmpty(newDtmx))
            {
                currNum = ComLib.getSecScreenCode();
            }
            // genero nuovo QR
            string qrUrl = getImageUrl();
            imgQrMain.ImageUrl = qrUrl;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                refreshCodPost();
                doUpdate();
                // primo: 1 minuto
                countDown = 60;
                SheetId = 0;
                itemDtmx = "IT";
            }
        }

        protected void timerRefresh_Tick(object sender, EventArgs e)
        {
            countDown--;
            if (countDown < 0)
            {
                refreshCodPost();
                // count-down successivi: 2 minuti
                countDown = 60 * 2;
            }
            setCurrData();
            doUpdate();
        }

        private void removeOldTemp()
        {
            var fileList = fileMover.obj.elencoFilesDir(Server.MapPath("~/temp"));
            foreach (var item in fileList)
            {
                // solo se NON sono placeholder o none...
                if (!item.Nome.Contains("none.pdf") && !item.Nome.Contains("PlaceHolder.file"))
                {
                    if (item.dataMod < DateTime.Now.AddHours(-1))
                    {
                        fileMover.deleteFile(Server.MapPath($"~/temp/{item.Nome}"));
                    }
                }
            }
        }

        /// <summary>
        /// Imposta dati correnti (Bunk / Sheet)
        /// </summary>
        private void setCurrData()
        {
            // recupero bunk corrente...
            DS_App.StackListRow currBunk = ComLib.getCurrBunk();
            if (currBunk != null)
            {
                DS_App.SheetListRow currSheet = ComLib.getCurrSheet(currBunk.BatchID, machine);
                if (currSheet != null)
                {
                    // se variato...
                    if (SheetId != currSheet.SheetID)
                    {
                        SheetId = currSheet.SheetID;
                    }
                }
            }
            else
            {
                SheetId = 0;
            }
        }
    }
}