using AppData;
using NKC_SDK;
using SteamWare;
using System;

namespace NKC_WF.WebUserControls
{
    public partial class cmp_unloadSmart : BaseUserControl
    {
        protected bool showBin
        {
            set
            {
                hfShowBin.Value = value.ToString();
            }
            get
            {
                bool answ = false;
                bool.TryParse(hfShowBin.Value, out answ);
                return answ;
            }
        }
        protected bool showCart
        {
            set
            {
                hfShowCart.Value = value.ToString();
            }
            get
            {
                bool answ = false;
                bool.TryParse(hfShowCart.Value, out answ);
                return answ;
            }
        }
        protected bool showSecOp
        {
            set
            {
                hfShowSecOp.Value = value.ToString();
            }
            get
            {
                bool answ = false;
                bool.TryParse(hfShowSecOp.Value, out answ);
                return answ;
            }
        }
        /// <summary>
        /// ID univoco da IP
        /// </summary>
        protected string DeviceId
        {
            set
            {
                hfDeviceId.Value = value;
            }
            get
            {
                return hfDeviceId.Value;
            }
        }
        /// <summary>
        /// Postazione attuale (per ora cablata)
        /// </summary>
        protected string PlaceId
        {
            get
            {
                return "WRK001";
            }
        }

        /// <summary>
        /// Sheet selezionato...
        /// </summary>
        protected int SheetID
        {
            set
            {
                hfSheetID.Value = value.ToString();
            }
            get
            {
                int answ = 0;
                int.TryParse(hfSheetID.Value, out answ);
                return answ;
            }
        }
        protected string secOp
        {
            get
            {
                return hfSecOp.Value;
            }
            set
            {
                hfSecOp.Value = value;
            }
        }
        /// <summary>
        /// Aggiorna dati correnti (IP, batch, sheet...)
        /// </summary>
        protected void updateCurrData()
        {
            // FORSE 5/5?!?
            var sheetList = DataLayer.man.taSHL.getByMLStatus(BatchId, 3, 5);
            if (sheetList.Count > 0)
            {
                SheetID = sheetList[0].SheetID;
            }
            DeviceId = ComLib.GetIPAddress().Replace(".", "0").Replace(":", "0");
        }
        /// <summary>
        /// Batch corrente...
        /// </summary>
        public int BatchId
        {
            set
            {
                hfBatchID.Value = value.ToString();
            }
            get
            {
                int answ = 0;
                int.TryParse(hfBatchID.Value, out answ);
                return answ;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                resetShowData();
                resetIcons();
                updateCurrData();
            }
            cmp_barcode.eh_doRefresh += Cmp_barcode_eh_doRefresh;
            cmp_barcode.eh_doReset += Cmp_barcode_eh_doReset;
            // resetto
            lblLastBCode.Text = "------";
            lblMessage.Text = "----";
            lblDestination.Text = "--";
        }

        private void resetShowData()
        {
            showCart = false;
            showBin = false;
            showSecOp = false;
        }

        /// <summary>
        /// Comando barcode letto
        /// </summary>
        protected string lastCmd
        {
            get
            {
                return hfLastBCode.Value;
            }
            set
            {
                hfLastBCode.Value = value;
                lastValidCmd = value;
            }
        }
        /// <summary>
        /// ULTIMO Comando barcode VALIDO (!="") letto
        /// </summary>
        protected string lastValidCmd
        {
            get
            {
                return hfLastValidBCode.Value;
            }
            set
            {
                // solo se è !=""
                if (!string.IsNullOrEmpty(value))
                {
                    hfLastValidBCode.Value = value;
                }
            }
        }
        private void Cmp_barcode_eh_doReset(object sender, EventArgs e)
        {
            resetIcons();
        }

        private void Cmp_barcode_eh_doRefresh(object sender, EventArgs e)
        {
            bool doRaiseEv = false;
            // processo evento..
            lastCmd = cmp_barcode.inputAcquired.ToUpper();
            doRaiseEv = processLastCmd(doRaiseEv);

            // reset comando
            cmp_barcode.inputAcquired = "";
            ComLib.man.resetSheetUnload(SheetID);
            // aggiorno...
            doUpdate();
        }

        private bool processLastCmd(bool doRaiseEv)
        {
            if (string.IsNullOrEmpty(lastCmd)) doRaiseEv = true;
            // processiamo barcode letto
            decodedData decoData = DataLayer.man.decodeBcode(lastCmd);
            switch (decoData.codeType)
            {
                case codeType.UNK:
                    cmp_barcode.showOutput("text-danger", $"Unknown Data: {decoData.rawData} --> no action");
                    resetSelection(false);
                    doRaiseEv = true;
                    break;
                case codeType.Item:
                    tryPickup(decoData.rawData);
                    cmp_barcode.showOutput("badge badge-success", $"Valid IT Code: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                case codeType.ItemGeneric:
                    tryPickup(decoData.rawData);
                    cmp_barcode.showOutput("badge badge-success", $"Valid IG Code: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                case codeType.Material:
                    cmp_barcode.showOutput("badge badge-warning", $"Material - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;
                case codeType.Sheet:
                    cmp_barcode.showOutput("badge badge-warning", $"Sheet - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;
                case codeType.Stack:
                    cmp_barcode.showOutput("badge badge-warning", $"BUNK - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;
                case codeType.OtherItem:
                    cmp_barcode.showOutput("badge badge-warning", $"Generic PART - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;
                case codeType.Batch:
                    cmp_barcode.showOutput("badge badge-warning", $"Batch - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;
                case codeType.Cart:
                    cmp_barcode.showOutput("badge badge-success", $"Valid CR Code: {decoData.description}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                case codeType.Bin:
                    cmp_barcode.showOutput("badge badge-success", $"Valid BN Code: {decoData.description}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                case codeType.SecScreen:
                    cmp_barcode.showOutput("badge badge-success", $"Valid Screen Code: {decoData.description}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                default:
                    cmp_barcode.showOutput("text-danger", $"Unknown Data: {decoData.rawData} --> no action");
                    resetSelection(false);
                    break;
            }

            return doRaiseEv;
        }
        /// <summary>
        /// Prova a fare pickup (SOLO SE il mio item è nel foglio corrente...)
        /// </summary>
        /// <param name="itemDtmx"></param>
        protected void tryPickup(string itemDtmx)
        {
            // salvo in item sel...
            updateCurrData();
            ComLib.saveItemPickup(SheetID, DeviceId, itemDtmx);
        }

        /// <summary>
        /// Processo il DataMatrix letto
        /// </summary>
        /// <param name="tipoCod"></param>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        private void processItemSuggestion(codeType tipoCod, string rawData, int codeInt)
        {
            DS_App.ItemListDataTable tabItem = null;
            // processo suggerimenti x ITEM / cart / bin dato suo RawData (Dtmx) e Cod univoco (intero)
            switch (tipoCod)
            {
                case codeType.Item:
                    tabItem = DataLayer.man.taIL.getBySearch(codeInt, rawData, 0, 999);
                    if (tabItem.Count == 1)
                    {
                        showItemDetail(true, tabItem[0], false);
                    }
                    else if (tabItem.Count == 0)
                    {
                        showItemDetail(false, null, true);
                    }
                    break;
                case codeType.ItemGeneric:
                    // PRIMA CERCA SE ne ho in stato 1..3
                    tabItem = DataLayer.man.taIL.getBySearch(0, rawData, 1, 3);
                    if (tabItem.Count == 0)
                    {
                        // se NON ne trovo cerci FINO a stato 5...
                        tabItem = DataLayer.man.taIL.getBySearch(0, rawData, 1, 5);
                    }
                    if (tabItem.Count == 1)
                    {
                        showItemDetail(true, tabItem[0], false);
                    }
                    else if (tabItem.Count == 0)
                    {
                        showItemDetail(false, null, true);
                    }
                    break;
                case codeType.Cart:
                    // verifico NON SIA richiesto PAINT
                    if (showBin)
                    {
                        displError("PAINT: BIN REQUESTED: please retry", true);
                    }
                    else
                    {
                        if (currCartTab.Count == 1)
                        {
                            // controllo se sia quello corretto
                            if (rawData != currCartTab[0].CartDtmx)
                            {
                                displError("INCORRECT CART: please retry", true);
                            }
                            else
                            {
                                // dichiaro che è depositato
                                DataLayer.man.taIL.updateStatus(itemIdSelected, 3, PlaceId);
                                lblDestination.Text = $"Item {itemIdSelected} PUT IN CART {rawData}";
                                resetSelection(false);
                            }
                        }
                    }
                    break;
                case codeType.Bin:
                    // verifico NON SIA richiesto PAINT
                    if (showCart)
                    {
                        displError("NOT PAINTED: CART REQUESTED: please retry", true);
                    }
                    else
                    {
                        if (currBinTab.Count == 1)
                        {
                            // controllo se sia quello corretto
                            if (rawData != currBinTab[0].BinDtmx)
                            {
                                displError("INCORRECT BIN: please retry", true);
                            }
                            else
                            {
                                // dichiaro che è depositato
                                DataLayer.man.taIL.updateStatus(itemIdSelected, 4, PlaceId);
                                lblDestination.Text = $"Item {itemIdSelected} PUT IN BIN {rawData}";
                                resetSelection(false);
                            }
                        }
                    }
                    break;
                case codeType.SecScreen:
                    // se item già letto
                    if (divItemDet.Visible)
                    {
                        int defaultSecScreenShowTimeout = memLayer.ML.CRI("defaultSecScreenShowTimeout");
                        ComLib.setSecScreenRequest(rawData, lblItemDtmx.Text, 60 * defaultSecScreenShowTimeout);
                        displMessage($"ITEM Sent to second screen | {lblItemDtmx.Text} for {defaultSecScreenShowTimeout} min", true);
                    }
                    else
                    {
                        // chiedo di leggere un ITEM prima...
                        displError("Please read ITEM before Screen and Retry", true);
                    }
                    break;
                default:
                    break;
            }


            // cerco su DB

            // certo lavorazioni accessorie

            // cerco destinazione CART/BIN

            // salvo in hiddenField

            // mostro output (compreso che mi aspetto entro 30 sec lettura cart/Bin)


        }
        /// <summary>
        /// Mostra INFO ed effettua reset vari...
        /// </summary>
        /// <param name="currMessage"></param>
        /// <param name="resetStatus"></param>
        protected void displMessage(string currMessage, bool resetStatus)
        {
            lblInfoMessage.Text = currMessage;
            divInfoMessage.Visible = true;
            resetSelection(resetStatus);
        }
        /// <summary>
        /// Mostra errore ed effettua reset vari...
        /// </summary>
        /// <param name="errorMessage"></param>
        /// <param name="resetStatus"></param>
        protected void displError(string errorMessage, bool resetStatus)
        {
            lblErrorMsg.Text = errorMessage;
            divItemError.Visible = true;
            resetSelection(resetStatus);
        }
        /// <summary>
        /// Reset selezione item + blocchi suggerimento + sel REDIS x pagina unload
        /// </summary>
        /// <param name="resetStatus"></param>
        protected void resetSelection(bool resetStatus)
        {
            if (resetStatus)
            {
                try
                {
                    // SE item esiste...
                    var tabItem = DataLayer.man.taIL.getBySearch(itemIdSelected, itemIdSelected.ToString(), 0, 999);
                    if (tabItem.Count == 1)
                    {
                        // riposto item a status 1...
                        DataLayer.man.taIL.updateStatus(itemIdSelected, 1, PlaceId);
                    }
                }
                catch
                { }
            }
            // elimino item sel...
            itemIdSelected = 0;
            resetShowData();
            ComLib.resetItemPickup(SheetID, DeviceId);
        }
        /// <summary>
        /// Mostra o nasconde dettaglio su ITEM letto
        /// </summary>
        /// <param name="v"></param>
        /// <param name="itemRow"></param>
        private void showItemDetail(bool showItem, DS_App.ItemListRow itemRow, bool showError)
        {
            resetShowData();
            divItemDet.Visible = showItem;
            divItemError.Visible = showError;
            if (showError)
            {
                displError("Item not found", true);
            }
            if (showItem)
            {
                lblItemCode.Text = itemRow.ItemExtCode;
                lblItemDesc.Text = itemRow.ItemDesc;
                lblItemDtmx.Text = itemRow.ItemDtmx;
                itemIdSelected = itemRow.ItemID;
                // CONTROLLO SIA in stato 1 --> worked, 2--> selected, 100--> parked...
                switch (itemRow.StatusID)
                {
                    case 0:
                        displError("ERROR: Item not ready", false);
                        break;
                    case 1:
                    case 2:
                    case 100:
                        // salvo che è in STATO 2 (picked up) 
                        DataLayer.man.taIL.updateStatus(itemRow.ItemID, 2, PlaceId);
                        // verifico cosa devo mostrare come PROX passaggio...
                        showCart = string.IsNullOrEmpty(itemRow.ProcessesReq);
                        showBin = (itemRow.ProcessesReq.Contains("PaintFlag"));
                        secOp = itemRow.PostProcList;
                        showSecOp = (!string.IsNullOrEmpty(secOp));
                        doUpdate();
                        break;
                    case 3:
                        displError("Item already on CART!", false);
                        break;
                    case 4:
                        // fino a concorrenza qta richiesta sposto, POI do errori
                        displError("ALL Item already scanned on BIN!", false);
                        break;
                    case 5:
                        displError("Item already at KIT STATION!", false);
                        break;
                    case 990:
                        displError("Item declared SCRAP!", false);
                        break;
                    case 991:
                        displError("Item declared SCRAP with CNC program created!", false);
                        break;
                    default:
                        displError("ERROR: Item status UNKNOWN!", false);
                        break;
                }
            }
            lbtResetSel.Visible = (itemIdSelected != 0);
        }

        public int itemIdSelected
        {
            get
            {
                int answ = 0;
                int.TryParse(hfItemID.Value, out answ);
                return answ;
            }
            set
            {
                hfItemID.Value = value.ToString();
                bool showBtn = value != 0;
                // fix visibilità
                lbtCancel.Visible = showBtn;
                lbtScrapped.Visible = showBtn;
                lbtParkArea.Visible = showBtn;
            }
        }

        private void resetIcons()
        {
            lblDestination.CssClass = "text-secondary";
            lblMessage.Text = "";
            lblDestination.Text = "";
            lblLastBCode.Text = "";
            lbtCancel.Visible = false;
            lbtScrapped.Visible = false;
            lbtParkArea.Visible = false;
            lbtResetSel.Visible = (itemIdSelected != 0);
        }

        protected DS_App.BinsDataTable currBinTab
        {
            get
            {
                return DataLayer.man.taBN.getByItemID(itemIdSelected);
            }
        }
        protected DS_App.CartsDataTable currCartTab
        {
            get
            {
                return DataLayer.man.taCR.getByItemID(itemIdSelected);
            }
        }

        private void doUpdate()
        {
            // reset grafico
            icnCart.Attributes.Remove("class");
            icnCart.Attributes.Add("class", "btn btn-sm btn-block btn-outline-secondary");
            icnBin.Attributes.Remove("class");
            icnBin.Attributes.Add("class", "btn btn-sm btn-block btn-outline-secondary");
            icnSecOp.Attributes.Remove("class");
            icnSecOp.Attributes.Add("class", "btn btn-sm btn-block btn-outline-secondary");

            // in base al secondo mostro uno o altro...
            if (showCart)
            {
                icnCart.Attributes.Remove("class");
                icnCart.Attributes.Add("class", "btn btn-sm btn-block btn-success");
                lblMessage.Text = "Item recognized";
                // controllo SE HO cart
                if (currCartTab.Count == 1)
                {
                    var cartRow = currCartTab[0];
                    // imposto OUT
                    lblDestination.Text = $"SEND TO CART <b>C{cartRow.CartIndex}</b> ({cartRow.CartDtmx})";
                }
                else
                {
                    lblDestination.Text = $"ERROR SEARCHING CART: {currCartTab.Count} found!";
                }
                lblDestination.CssClass = "text-success";
            }
            else if (showBin)
            {
                icnBin.Attributes.Remove("class");
                icnBin.Attributes.Add("class", "btn btn-sm btn-block btn-primary");
                lblMessage.Text = "Item recognized";
                if (currBinTab.Count == 1)
                {
                    var binRow = currBinTab[0];
                    lblDestination.Text = $"SEND TO BIN <b>B{binRow.BinIndex}</b> ({binRow.BinDtmx})";
                }
                else
                {
                    lblDestination.Text = $"ERROR SEARCHING BIN: {currBinTab.Count} found!";
                }
                lblDestination.CssClass = "text-primary";
            }
            if (showSecOp)
            {
                icnSecOp.Attributes.Remove("class");
                icnSecOp.Attributes.Add("class", "btn btn-sm btn-block btn-info");
                lblMessage.Text = "Item recognized";
                lblLastBCode.Text = $"DO SEC OP: {secOp}";
                lblLastBCode.CssClass = "text-info";
            }
            // fix btn reset!
            lbtResetSel.Visible = (itemIdSelected != 0);
        }

        protected void lbtCancel_Click(object sender, EventArgs e)
        {
            // resetto item selezionato...
            DataLayer.man.taIL.updateStatus(itemIdSelected, 1, PlaceId);
            resetSelection(true);
            showItemDetail(false, null, false);
        }
        protected void lbtResetSel_Click(object sender, EventArgs e)
        {
            var tabSheet = DataLayer.man.taSHL.getByItemID(itemIdSelected);
            if (tabSheet.Count == 1)
            {
                resetShowData();
                // resetto sheet selezionato...
                DataLayer.man.taIL.updateSheetStatusPU(tabSheet[0].SheetID, PlaceId);
                resetSelection(true);
                showItemDetail(false, null, false);
            }
        }
        /// <summary>
        /// imposto a parcheggiato
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtParkArea_Click(object sender, EventArgs e)
        {
            // resetto item selezionato...
            DataLayer.man.taIL.updateStatus(itemIdSelected, 100, PlaceId);
            resetSelection(true);
            showItemDetail(false, null, false);
            lblMessage.Text = "Item Parked";
        }
        /// <summary>
        /// Imposto come danneggiato/scrapped da rilavorare offline
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtScrapped_Click(object sender, EventArgs e)
        {
            // resetto item selezionato...
            DataLayer.man.taIL.updateStatus(itemIdSelected, 990, PlaceId);
            lblMessage.Text = "Item Set SCRAPPED";
            // rirprocesso barcode...
            lastCmd = lastValidCmd;
            processLastCmd(false);
        }
    }
}