using AppData;
using NKC_SDK;
using SteamWare;
using System;
using System.Data;
using System.Linq;

namespace NKC_WF.WebUserControls
{
    public partial class cmp_kittingSmart : BaseUserControl
    {
        /// <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;
            }
        }
        /// <summary>
        /// Aggiorna dati correnti (IP, batch, sheet...)
        /// </summary>
        protected void updateCurrData()
        {
            // FORSE 5/5?!?
            var sheetList = DataLayer.man.taSHL.getByMLStatus(PackListID, 3, 5);
            if (sheetList.Count > 0)
            {
                SheetID = sheetList[0].SheetID;
            }
            DeviceId = ComLib.GetIPAddress().Replace(".", "0").Replace(":", "0");
        }
        /// <summary>
        /// PackList corrente...
        /// </summary>
        public int PackListID
        {
            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)
            {
                lastObject = "";
                resetShowData();
                resetIcons();
                updateCurrData();
            }
            cmp_barcode.eh_doRefresh += Cmp_barcode_eh_doRefresh;
            cmp_barcode.eh_doReset += Cmp_barcode_eh_doReset;
            cmp_KS_BinCart.eh_doRefresh += cmp_KS_BinCart_eh_doRefresh;
            cmp_KS_OtherItemsCart.eh_doRefresh += cmp_KS_OtherItemsCart_eh_doRefresh;
            cmp_KS_Items.eh_doRefresh += cmp_KS_Items_eh_doRefresh;
        }

        private void cmp_KS_Items_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("PART added", true);
            // resetto BIN & CART
            resetBin();
            resetCart();
            resetItem();
        }

        private void cmp_KS_OtherItemsCart_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("Other PART added", true);
            // resetto BIN & CART
            resetBin();
            resetCart();
            resetItem();
        }

        private void cmp_KS_BinCart_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("PAINT PART added", true);
            // resetto BIN & CART
            resetBin();
            resetCart();
            resetItem();
        }

        private void resetShowData()
        {
            cmp_KS_Cart.Visible = false;
            cmp_KS_BinCart.Visible = false;
            cmp_KS_OtherItemsCart.Visible = false;
            cmp_KS_Items.Visible = false;
        }

        /// <summary>
        /// Comando barcode letto
        /// </summary>
        protected string lastCmd
        {
            get
            {
                return hfLastBCode.Value;
            }
            set
            {
                hfLastBCode.Value = value;
                lastValidCmd = value;
            }
        }
        /// <summary>
        /// Ultimo object letto
        /// </summary>
        protected string lastObject
        {
            get
            {
                return hfLastObject.Value;
            }
            set
            {
                hfLastObject.Value = 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 = "";
            // aggiorno...
            doUpdate();
            if (doRaiseEv)
            {
                raiseEvent();
            }
        }

        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:
                    cmp_barcode.showOutput("badge badge-success", $"Valid IT Code: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                case codeType.ItemGeneric:
                    cmp_barcode.showOutput("badge badge-success", $"Valid IG Code: {decoData.rawData}");
                    //processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                case codeType.OtherItem:
                    cmp_barcode.showOutput("badge badge-success", $"Valid Generic PART 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.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);
                    doRaiseEv = true;
                    break;
                case codeType.Bin:
                    cmp_barcode.showOutput("badge badge-warning", $"BIN NOT PAINTED - Ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;
                case codeType.BinProcessed:
                    cmp_barcode.showOutput("badge badge-success", $"Valid BP 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>
        /// 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;
            divInfo.Visible = false;
            // processo suggerimenti x ITEM / cart / bin dato suo RawData (Dtmx) e Cod univoco (intero)
            switch (tipoCod)
            {
                case codeType.Cart:
                    // primo step: verifico dal codice CART l'ordine da cui deriva...
                    var tabOrdini = DataLayer.man.taOL.getByCart(rawData);
                    if (tabOrdini.Count == 0)
                    {
                        displError($"CART: Order not found for Cart {rawData}, {traduci("ErrPleaseRetry")}", true);
                        resetCart();
                    }
                    else
                    {
                        var rigaOrd = tabOrdini[0];
                        // ora si va sulla tab delle PackListDet x cercare ordine legato al Cart... prendo quella attiva!
                        var tabPLD = DataLayer.man.taPLD.getRunByOrdExtCode(rigaOrd.OrderExtCode);
                        // controllo se trovo righe...
                        if (tabPLD.Count == 0)
                        {
                            displError($"KIT REQuest: PackList not found for Cart {rawData} --> OrdExtCode {rigaOrd.OrderExtCode}, {traduci("ErrPleaseRetry")}", true);
                            resetCart();
                        }
                        else
                        {
                            // mostro CART!
                            setCart(rawData, codeInt);
                            // verifico se il cart sia già stato messo in scarico (in quel caso dico già ok...)
                            var tabLog = DataLayer.man.taPLog.getByCartId(codeInt);
                            if (tabLog.Count > 0)
                            {
                                // verifico se sia completo --> reset... altrimenti lascio così...
                                var tabCOK = DataLayer.man.taCOK.GetData();
                                // cerco se sia "green" numWait + numReady + numOtherWait = 0
                                var tabGreen = tabCOK.Where(x => (x.NumPzWaiting + x.NumPzBinAvail + x.OtherQtyWait == 0) && x.CartDtmx == rawData).ToList();
                                if (tabGreen.Count > 0)
                                {
                                    // verifico se sia SECONDA lettura
                                    if (lastObject == rawData)
                                    {
                                        // --> metto cart in scarico e registro LOG come se avesse appena letto 1:1 ogni Dtmx
                                        DataLayer.man.taPLog.closeCart(codeInt);
                                        // mostro che ho fatto
                                        displInfo($"OK: CART removed {rawData}", true);
                                        lastObject = "";
                                        // resetto BIN & CART
                                        resetBin();
                                        resetCart();
                                    }
                                    else
                                    {
                                        lastObject = rawData;
                                        displInfo($"Cart already completed, please read CART another time: Cart {rawData}", true);
                                    }
                                    resetCart();
                                }
                            }
                            else
                            {
                                // recupero da tab di check complessiva
                                var tabPLCheck = DataLayer.man.taPLC.GetData(rawData);
                                if (tabPLCheck.Count == 0)
                                {
                                    displError($"ERROR evaluating CART: {rawData}", true);
                                    resetCart();
                                }
                                else
                                {
                                    var rigaCheck = tabPLCheck[0];
                                    // verifico penalty (vedere stored: pezzi da leggere >= pezzi del cart...)
                                    if (rigaCheck.NumPenalty == 0)
                                    {
                                        // verifico se sia SECONDA lettura
                                        if (lastObject == rawData)
                                        {
                                            // --> metto cart in scarico e registro LOG come se avesse appena letto 1:1 ogni Dtmx
                                            DataLayer.man.taPLog.acquireCart(rawData, currIpAddress(), user_std.UtSn.userNameAD);
                                            displInfo($"OK: CART acquired {rawData} - item confirmed", true);
                                            lastObject = "";
                                            // eseguo comando x spostare i PAINT nel cart corretto...
                                            DataLayer.man.taKL.updateCartForBin(rawData);
                                            // resetto BIN & CART
                                            resetBin();
                                            resetCart();
                                        }
                                        else
                                        {
                                            lastObject = rawData;
                                            displError($"Please read CART another time: Cart {rawData}", true);
                                        }
                                    }
                                    else
                                    {
                                        displError($"ERROR CART contains KIT already on download: {rawData}", true);
                                        resetCart();
                                    }
                                }
                            }
                        }
                    }
                    break;
                case codeType.BinProcessed:
                    // recupero la tab OKIB x iniziare a controllare i dati...
                    var tabOKIB = DataLayer.man.taOKIB.getByBinDtmxProc(rawData);
                    // PRIMO: verifico SE ho delle righe valide...
                    if (tabOKIB.Count == 0)
                    {
                        displError($"BIN: Code not found {rawData}, {traduci("ErrPleaseRetry")}", true);
                        // reset preliminare
                        resetBin();
                    }
                    else
                    {
                        var listPainted = tabOKIB.Where(x => !x.IsPaintDateNull()).ToList();
                        if (listPainted.Count == 0)
                        {
                            displError($"BIN: Paint Date missing for item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}, {traduci("ErrPleaseRetry")}", true);
                            // reset preliminare
                            resetBin();
                        }
                        else
                        {
                            var listAvailable = tabOKIB.Where(x => !x.IsPaintDateNull() && x.IsOnCartDateNull()).ToList();
                            if (listAvailable.Count == 0)
                            {
                                displError($"BIN: No item available for pickup on target CART for code {rawData} | item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}, {traduci("ErrPleaseRetry")}", true);
                                // reset preliminare
                                resetBin();
                            }
                            else
                            {
                                // verifico SE ci sia ALMENO UN CART in postazione (iniziato KIT ma NON finito)...
                                var listCartAvailable = tabOKIB.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull()).ToList();
                                if (listCartAvailable.Count == 0)
                                {
                                    displError($"BIN: No CART available to proceed: {rawData} | item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}", true);
                                    // reset preliminare
                                    resetBin();
                                }
                                else
                                {
                                    // mostro BIN!
                                    setBin(rawData, codeInt);


                                    // verifico se il Bin sia già stato messo in scarico (in quel caso dico già ok...)
                                    var listBinAcquired = tabOKIB.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull() && !x.IsBinKitStartNull()).ToList();
                                    if (listBinAcquired.Count > 0)
                                    {
                                        // verifico se sia GIA' stato completato KIT...
                                        var listBinNotCompleted = tabOKIB.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull() && !x.IsBinKitStartNull() && x.IsBinKitEndNull()).ToList();
                                        if (listBinNotCompleted.Count == 0)
                                        {
                                            displError($"BIN: already completed: {rawData} | item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}", true);
                                            // reset preliminare
                                            resetBin();
                                        }
                                    }
                                    else
                                    {
                                        // processing...
                                        if (lastObject == rawData)
                                        {
                                            // seconda lettura x indicare in scarico
                                            DataLayer.man.taBN.updateKitting(codeInt, true, false);
                                            // resetto BIN & CART
                                            resetBin();
                                            resetCart();
                                        }
                                        else
                                        {
                                            // chiedo seconda lettura
                                            lastObject = rawData;
                                            displError($"Please read BIN another time: BIN {rawData}", true);
                                            // reset preliminare
                                            resetBin();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;
                case codeType.Item:
                    // recupero la tab ITEMS x iniziare a controllare i dati...
                    tabItem = DataLayer.man.taIL.getBySearch(codeInt, rawData, 0, 999);
                    if (tabItem.Count == 0)
                    {
                        displError($"{traduci("ErrPartNotFound")} {rawData}, {traduci("ErrPleaseRetry")}", true);
                        showItemDetail(false, null, true);
                    }
                    else if (tabItem.Count == 1)
                    {
                        var itemRow = tabItem[0];
                        showItemDetail(true, itemRow, false);
                        // verifico se ITEM sia o meno stato caricato sul CART x delivery finale
                        if (!itemRow.IsOnCartDateNull())
                        {
                            // se caricato --> mostro che è già a posto
                            displError($"{traduci("ErrPartAlreadyOnCart")} {rawData}, {traduci("ErrPleaseRetry")}", true);
                            resetItem();
                        }
                        else
                        {
                            // imposto controllo...
                            cmp_KS_Items.ItemID = codeInt;
                            cmp_KS_Items.NeedSecOp = !string.IsNullOrEmpty(itemRow.PostProcList);
                            cmp_KS_Items.NeedPaint = !string.IsNullOrEmpty(itemRow.ProcessesReq) && itemRow.ProcessesReq == "PaintFlag";
                            // controllo!
                            cmp_KS_Items.doUpdate();
                        }
                    }
                    break;
                case codeType.OtherItem:
                    // recupero la tab OKOI x iniziare a controllare i dati...
                    var tabOKOI = DataLayer.man.taOKOI.getByOtherItemDtmx(rawData);
                    // PRIMO: verifico SE ho delle righe valide...
                    if (tabOKOI.Count == 0)
                    {
                        displError($"{traduci("ErrPartNotFound")} {rawData}, {traduci("ErrPleaseRetry")}", true);
                        // reset preliminare
                        resetOtherItem();
                    }
                    else
                    {
                        var listAvailable = tabOKOI.Where(x => x.IsOnCartDateNull()).ToList();
                        if (listAvailable.Count == 0)
                        {
                            displError($"{traduci("ErrPartNoItemAvail")} {rawData} | item {tabOKOI[0].OtherItemDesc} | order {tabOKOI[0].OrderExtCode}, {traduci("ErrPleaseRetry")}", true);
                            // reset preliminare
                            resetOtherItem();
                        }
                        else
                        {
                            // verifico SE ci sia ALMENO UN CART in postazione (iniziato KIT ma NON finito)...
                            var listCartAvailable = tabOKOI.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull()).ToList();
                            if (listCartAvailable.Count == 0)
                            {
                                displError($"{traduci("ErrPartNoCartAvail")}: {rawData} | item {tabOKOI[0].OtherItemDesc} | order {tabOKOI[0].OrderExtCode}", true);
                                // reset preliminare
                                resetOtherItem();
                            }
                            else
                            {
                                // mostro OtherItem!
                                setOtherItem(rawData, codeInt);
                            }
                        }
                    }
                    break;
                default:
                    lastObject = "";
                    break;
            }



        }
        /// <summary>
        /// Imposta il codice Item sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        private void setItem(string rawData, int codeInt)
        {
            itemIdSelected = codeInt;
            cmp_KS_Items.ItemID = codeInt;
            cmp_KS_Items.ItemDtmx = rawData;
            cmp_KS_Items.doUpdate();
            fixVisibility();
        }
        /// <summary>
        /// Imposta il codice OtherItem sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        private void setOtherItem(string rawData, int codeInt)
        {
            cmp_KS_OtherItemsCart.OtherItemID = codeInt;
            cmp_KS_OtherItemsCart.OtherItemDtmx = rawData;
            cmp_KS_OtherItemsCart.doUpdate();
            fixVisibility();
        }

        /// <summary>
        /// Imposta il bin sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        private void setBin(string rawData, int codeInt)
        {
            cmp_KS_BinCart.BinID = codeInt;
            cmp_KS_BinCart.BinDtmx = rawData;
            cmp_KS_BinCart.doUpdate();
            fixVisibility();
        }
        /// <summary>
        /// Imposta il cart sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        private void setCart(string rawData, int codeInt)
        {
            cmp_KS_BinCart.CartID = codeInt;
            cmp_KS_BinCart.CartDtmx = rawData;
            cmp_KS_BinCart.doUpdate();
            cmp_KS_OtherItemsCart.CartID = codeInt;
            cmp_KS_OtherItemsCart.CartDtmx = rawData;
            cmp_KS_OtherItemsCart.doUpdate();
            cmp_KS_Cart.CartID = codeInt;
            cmp_KS_Cart.CartDtmx = rawData;
            cmp_KS_Cart.doUpdate();
            cmp_KS_Items.CartID = codeInt;
            cmp_KS_Items.CartDtmx = rawData;
            cmp_KS_Items.doUpdate();
            fixVisibility();
        }

        private void resetBin()
        {
            cmp_KS_BinCart.BinID = 0;
            fixVisibility();
        }

        private void resetCart()
        {
            cmp_KS_BinCart.CartID = 0;
            cmp_KS_OtherItemsCart.CartID = 0;
            cmp_KS_Cart.CartID = 0;
            cmp_KS_Items.CartID = 0;
            fixVisibility();
        }
        private void resetOtherItem()
        {
            cmp_KS_OtherItemsCart.OtherItemID = 0;
            fixVisibility();
        }
        private void resetItem()
        {
            itemIdSelected = 0;
            cmp_KS_Items.ItemID = 0;
            fixVisibility();
        }

        /// <summary>
        /// Mostra INFO ed effettua reset vari...
        /// </summary>
        /// <param name="infoMessage"></param>
        /// <param name="resetStatus"></param>
        protected void displInfo(string infoMessage, bool resetStatus)
        {
            lblSuccessMsg.Text = infoMessage;
            divError.Visible = false;
            divInfo.Visible = true;
            resetSelection(resetStatus);
        }
        /// <summary>
        /// Mostra ERROR ed effettua reset vari...
        /// </summary>
        /// <param name="errorMessage"></param>
        /// <param name="resetStatus"></param>
        protected void displError(string errorMessage, bool resetStatus)
        {
            lblErrorMsg.Text = errorMessage;
            divError.Visible = true;
            divInfo.Visible = false;
            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)
                    {
                        // riporto 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="showItem"></param>
        /// <param name="itemRow"></param>
        /// <param name="showError"></param>
        private void showItemDetail(bool showItem, DS_App.ItemListRow itemRow, bool showError)
        {
            resetShowData();
            divItemDet.Visible = showItem;
            divError.Visible = showError;
            if (showError)
            {
                displError("Item not found", true);
            }
            if (showItem)
            {
                lblItemCode.Text = itemRow.ItemExtCode;
                lblItemDesc.Text = itemRow.ItemDesc;
                lblItemDtmx.Text = itemRow.ItemDtmx;
                // cerco kit --> cart...
                string cartDtmx = "-";
                try
                {
                    var tabCart = DataLayer.man.taCR.getByItemID(itemRow.ItemID);
                    if (tabCart != null && tabCart.Count > 0)
                    {
                        cartDtmx = tabCart[0].CartDtmx;
                    }
                }
                catch
                { }
                lblItemCartDtmx.Text = cartDtmx;
                setItem(itemRow.ItemDtmx, 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);
                        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;
            }
        }


        private void resetIcons()
        {
            lblDestination.CssClass = "text-secondary";
            lblMessage.Text = "";
            lblDestination.Text = "";
            lblLastBCode.Text = "";
            lbtCancel.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()
        {
            fixVisibility();
        }

        private void fixVisibility()
        {
            // reset grafico
            cmp_KS_Cart.Visible = cmp_KS_Cart.CartID > 0 && (cmp_KS_BinCart.BinID + cmp_KS_OtherItemsCart.OtherItemID + cmp_KS_Items.ItemID == 0);
            cmp_KS_BinCart.Visible = cmp_KS_BinCart.BinID > 0;
            cmp_KS_OtherItemsCart.Visible = cmp_KS_OtherItemsCart.OtherItemID > 0;
            cmp_KS_Items.Visible = cmp_KS_Items.ItemID > 0;
            // 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);
            }
        }

    }
}