using AppData;
using NKC_SDK;
using SteamWare;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NKC_WF.WebUserControls
{
    /// <summary>
    /// Modalità operativa su KittingSmartAdvanced
    /// </summary>
    public enum KSAdMode
    {
        ND = 0,
        InvalidPart,
        InvalidCart,
        RevalidPart
    }

    public partial class cmp_kittingSmartAdvInvalid : BaseUserControl
    {
        #region Protected Properties

        /// <summary>
        /// CartID selezionato
        /// </summary>
        protected int CartID
        {
            get
            {
                int answ = 0;
                int.TryParse(hfCartId.Value, out answ);
                return answ;
            }
            set
            {
                hfCartId.Value = value.ToString();
                cmp_KS_Cart.CartID = value;
                cmp_KS_Cart.doUpdate();
            }
        }

        protected string ItemDtmx
        {
            get
            {
                return hfItemDtmx.Value;
            }
            set
            {
                hfItemDtmx.Value = value;
            }
        }

        protected string ItemExtCode
        {
            get
            {
                return hfItemExtCode.Value;
            }
            set
            {
                hfItemExtCode.Value = value;
            }
        }

        /// <summary>
        /// ItemID selezionato
        /// </summary>
        protected int ItemID
        {
            get
            {
                int answ = 0;
                int.TryParse(hfItemId.Value, out answ);
                return answ;
            }
            set
            {
                hfItemId.Value = value.ToString();
                cmp_ItemDet.ItemId = value;
                cmp_ItemDet.doUpdate();
            }
        }

        /// <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;
                }
            }
        }

        #endregion Protected Properties

        #region Public Properties

        public KSAdMode currMode
        {
            get
            {
                KSAdMode answ = KSAdMode.ND;
                try
                {
                    answ = (KSAdMode)Enum.Parse(typeof(KSAdMode), hfMode.Value);
                }
                catch
                { }
                return answ;
            }
            set
            {
                hfMode.Value = value.ToString();
                fixDisplay();
            }
        }

        #endregion Public Properties

        #region Private Methods

        private void checkPartCart()
        {
            // reset preliminare
            lbtInvalidateCart.Visible = false;
            lbtInvalidatePartCart.Visible = false;
            switch (currMode)
            {
                case KSAdMode.InvalidCart:
                    // verifico il MODO: se CART --> mostro button x invalidare ALL
                    lbtInvalidateCart.Visible = true;
                    lbtInvalidateCart.DataBind();
                    break;

                case KSAdMode.InvalidPart:
                    // se SONO in modalità invalid part/cart ho part + cart mostro button
                    if (ItemID > 0 && CartID > 0)
                    {
                        lbtInvalidatePartCart.Visible = true;
                        lbtInvalidatePartCart.DataBind();
                    }
                    else
                    {
                        lbtInvalidatePartCart.Visible = false;
                    }
                    break;

                case KSAdMode.RevalidPart:
                    // se son in modalità revalidazione...
                    if (ItemID > 0 && CartID > 0)
                    {
                        // acquisisco...
                        DLMan.taPLog.acquireItems(ItemID, CartID, currIpAddress, user_std.UtSn.userNameAD);
                        lgInfo($"cmp_KittingSmartAdvInvalid | taPLog.acquireItems | ItemID : {ItemID} | CartID: {CartID} | user: {user_std.UtSn.userNameAD} | IP: {currIpAddress}");
                        // resetto (solo cart)
                        CartID = 0;
                        ItemID = 0;
                        // mostro messaggio...
                        string message = $"{ItemDtmx} {traduci("Part")} {ItemExtCode}  {traduci("PutInCart")} {cmp_KS_Cart.CartDtmx}";
                        displInfo(message);
                    }

                    break;

                case KSAdMode.ND:
                default:
                    break;
            }
        }

        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 = "";
            cmp_barcode.resetInput();
            // aggiorno...
            doUpdate();
            if (doRaiseEv)
            {
                raiseEvent();
            }
        }

        private void fixDisplay()
        {
            lblPart.Visible = false;
            lblCart.Visible = false;
            lblRevalid.Visible = false;
            lbtInvalidateCart.Visible = false;
            lbtInvalidatePartCart.Visible = false;
            switch (currMode)
            {
                case KSAdMode.InvalidPart:
                    lblPart.Visible = true;
                    break;

                case KSAdMode.InvalidCart:
                    lblCart.Visible = true;
                    break;

                case KSAdMode.RevalidPart:
                    lblRevalid.Visible = true;
                    break;

                case KSAdMode.ND:
                default:
                    break;
            }
        }

        private void fixVisibility()
        {
            // reset grafico
            cmp_KS_Cart.Visible = CartID > 0;
            checkPartCart();
        }

        /// <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)
        {
            divInfo.Visible = false;
            divError.Visible = false;
            DataLayer DLMan = new DataLayer();
            // 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 tabCart = DLMan.taCOK.getByKey(codeInt);
                    if (tabCart.Count == 0)
                    {
                        displError($"{traduci("KS_ADV_CartNotFound")} {rawData}, {traduci("ErrPleaseRetry")}");
                        resetCart();
                    }
                    else
                    {
                        var rigaCart = tabCart[0];
                        // verifico il cart NON ABBIA FINITO il KITTING (start ma NON end)
                        if (!rigaCart.IsKittingEndNull())
                        {
                            displError($"{traduci("KS_ADV_CartAlreadyKitted")} {rawData} --> OrdExtCode {rigaCart.OrderExtCode}, {traduci("ErrPleaseRetry")}");
                            resetCart();
                        }
                        else
                        {
                            // se non è al kitting non può resettare
                            if (rigaCart.IsKittingStartNull())
                            {
                                displError($"{traduci("KS_ADV_CartNotKitting")} {rawData} --> OrdExtCode {rigaCart.OrderExtCode}, {traduci("ErrPleaseRetry")}");
                                resetCart();
                            }
                            else
                            {
                                // mostro CART!
                                string descr = "-";
                                try
                                {
                                    descr = rigaCart.OrderExtCode;
                                }
                                catch
                                { }
                                setCart(rawData, codeInt, descr);
                                // verifico cosa mostrare/fare
                                checkPartCart();
                            }
                        }
                    }
                    break;

                case codeType.Item:
                    if (currMode == KSAdMode.InvalidCart)
                    {
                        displError($"{traduci("KS_ADV_WrongMode")} {rawData} --> {traduci("ErrPleaseRetry")}");
                        resetItem();
                    }
                    else
                    {
                        // verifico item esistente
                        var tabItems = DLMan.taIL.getByKey(codeInt);
                        if (tabItems.Count == 0)
                        {
                            displError($"{traduci("KS_ADV_ItemNotFound")} {rawData}, {traduci("ErrPleaseRetry")}");
                            resetItem();
                        }
                        else
                        {
                            setItem(rawData, codeInt, tabItems[0].ItemExtCode);
                            // verifico cosa mostrare/fare
                            checkPartCart();
                        }
                    }
                    break;

                case codeType.OtherItem:
                    break;

                default:
                    lastObject = "";
                    break;
            }
        }

        private bool processLastCmd(bool doRaiseEv)
        {
            if (string.IsNullOrEmpty(lastCmd)) doRaiseEv = true;
            // processiamo barcode letto
            decodedData decoData = DLMan.decodeBcode(lastCmd);
            switch (decoData.codeType)
            {
                case codeType.Item:
                    cmp_barcode.showOutput(cssClass.success, $"Valid IT Code: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;

                case codeType.OtherItem:
                    cmp_barcode.showOutput(cssClass.success, $"Valid Generic PART Code: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;

                case codeType.Cart:
                    cmp_barcode.showOutput(cssClass.success, $"{decoData.description}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    doRaiseEv = true;
                    break;

                default:
                    cmp_barcode.showOutput(cssClass.danger, $"{traduci("UnknownData")} {decoData.rawData} {traduci("NoAction")}");
                    resetSelection();
                    break;
            }
            return doRaiseEv;
        }

        private void resetCart()
        {
            CartID = 0;
            fixVisibility();
        }

        private void resetItem()
        {
            ItemID = 0;
            fixVisibility();
        }

        /// <summary>
        /// Imposta il cart sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        /// <param name="Description"></param>
        private void setCart(string rawData, int codeInt, string Description)
        {
            cmp_KS_Cart.CartDtmx = rawData;
            cmp_KS_Cart.CartDesc = Description;
            CartID = codeInt;
            fixVisibility();
        }

        /// <summary>
        /// Imposta ITEM sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        /// <param name="itemExtCode"></param>
        private void setItem(string rawData, int codeInt, string itemExtCode)
        {
            // salvo item e ext code...
            ItemExtCode = itemExtCode;
            ItemDtmx = rawData;
            ItemID = codeInt;
            fixVisibility();
        }

        #endregion Private Methods

        #region Protected Methods

        /// <summary>
        /// Mostra ERROR ed effettua reset vari...
        /// </summary>
        /// <param name="errorMessage"></param>
        protected void displError(string errorMessage)
        {
            lblErrorMsg.Text = errorMessage;
            divError.Visible = true;
            divInfo.Visible = false;
            resetSelection();
        }

        /// <summary>
        /// Mostra INFO ed effettua reset vari...
        /// </summary>
        /// <param name="infoMessage"></param>
        protected void displInfo(string infoMessage)
        {
            lblSuccessMsg.Text = infoMessage;
            divError.Visible = false;
            divInfo.Visible = true;
            resetSelection();
        }

        protected void doUpdate()
        {
        }

        protected void lbtInvalidateCart_Click(object sender, EventArgs e)
        {
            // esegue la stored di reset dell'intero cart...
            DLMan.taIL.invalidateByCart(CartID, PlaceCod);
            // resetto
            resetShowData();
            raiseReset();
        }

        protected void lbtInvalidatePartCart_Click(object sender, EventArgs e)
        {
            // solo se ho in sessione dati...
            if (ItemID > 0 && CartID > 0 && !string.IsNullOrEmpty(ItemExtCode))
            {
                // esegue la stored di reset delle PART con quel ExtCode nel cart...
                DLMan.taIL.invalidateByPartCart(CartID, ItemExtCode, PlaceCod);
            }
            // resetto
            resetShowData();
            Response.Redirect(Request.RawUrl);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                resetShowData();
            }
            cmp_barcode.eh_doRefresh += cmp_barcode_eh_doRefresh;
            PlaceCod = "ND";
        }

        protected void resetSelection()
        {
            resetCart();
            resetItem();
        }

        #endregion Protected Methods

        #region Public Methods

        public void resetShowData()
        {
            CartID = 0;
            ItemID = 0;
            lastObject = "";
            ItemExtCode = "";
            cmp_barcode.resetMessage();
            cmp_barcode.resetInput();
            divError.Visible = false;
            divInfo.Visible = false;
            fixVisibility();
        }

        #endregion Public Methods
    }
}