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

namespace NKC_WF.WebUserControls
{
    public partial class cmp_labelsPrint : BaseUserControl
    {
        /// <summary>
        /// ID univoco da IP
        /// </summary>
        protected string DeviceId
        {
            set
            {
                hfDeviceId.Value = value;
            }
            get
            {
                return hfDeviceId.Value;
            }
        }

        /// <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?!?
            DataLayer DLMan = new DataLayer();
            var sheetList = DLMan.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;
        }

        private void cmp_KS_OtherItemsCart_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("Other PART added", true);
        }

        private void cmp_KS_BinCart_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("PAINT PART added", true);
        }

        private void resetShowData()
        {
            lbtPrintLabels.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 = DLMan.decodeBcode(lastCmd);
            switch (decoData.codeType)
            {
                case codeType.Item:
                    cmp_barcode.showOutput(cssClass.success, $"IT {traduci("ValidCode")}: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;
                case codeType.ItemGeneric:
                    cmp_barcode.showOutput(cssClass.success, $"{traduci("ItemGeneric")} - {traduci("Ignored")}: {decoData.rawData}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.OtherItem:
                    cmp_barcode.showOutput(cssClass.success, $"{traduci("OtherPart")} - {traduci("Ignored")}: {decoData.rawData}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.Material:
                    cmp_barcode.showOutput(cssClass.warning, $"{traduci("Material")} - {traduci("Ignored")}: {decoData.description}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.Sheet:
                    cmp_barcode.showOutput(cssClass.warning, $"{traduci("Sheet")} - {traduci("Ignored")}: {decoData.description}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.Stack:
                    cmp_barcode.showOutput(cssClass.warning, $"{traduci("Sheet")}BUNK - {traduci("Ignored")}: {decoData.description}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.Batch:
                    cmp_barcode.showOutput(cssClass.warning, $"{traduci("Sheet")}BATCH - {traduci("Ignored")}: {decoData.description}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.Cart:
                    cmp_barcode.showOutput(cssClass.warning, $"{traduci("Sheet")}CART - {traduci("Ignored")}: {decoData.description}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.Bin:
                    cmp_barcode.showOutput(cssClass.warning, $"{traduci("BinNotPainted")} - {traduci("Ignored")}: {decoData.description}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.BinProcessed:
                    cmp_barcode.showOutput(cssClass.warning, $"{traduci("BinPainted")} - {traduci("Ignored")}: {decoData.description}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    break;
                case codeType.UNK:
                default:
                    cmp_barcode.showOutput(cssClass.danger, $"{traduci("UnknownData")}: {decoData.rawData} --> {traduci("NoValiAction")}");
                    resetDisplay(true);
                    doRaiseEv = true;
                    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;
            DataLayer DLMan = new DataLayer();
            divInfo.Visible = false;
            // processo suggerimenti x ITEM / cart / bin dato suo RawData (Dtmx) e Cod univoco (intero)
            switch (tipoCod)
            {
                case codeType.Item:
                    tabItem = DLMan.taIL.getBySearch(codeInt, rawData, 0, 999);
                    if (tabItem.Count == 1)
                    {
                        showItemDetail(true, tabItem[0], false);
                    }
                    else if (tabItem.Count == 0)
                    {
                        showItemDetail(false, null, true);
                    }
                    // mostro print!
                    lbtPrintLabels.Visible = true;
                    break;
                default:
                    lastObject = "";
                    // nascondo print!
                    lbtPrintLabels.Visible = false;

                    break;
            }



        }
        protected void lbtPrintLabels_Click(object sender, EventArgs e)
        {
            // chiamo procedura stampa report x etichette dei pezzi lavorati offline
            string printer = DLMan.getPrinter("PC-MACHINE-PARTS");
            // mando stampa....
            bool fatto = DLMan.stampaDoc(itemIdSelected.ToString(), printer, tipoDocumento.docPart, Request.UserHostName);

            lgInfo($"PRINT req for labelsPrint | codeInt : {itemIdSelected} | currQueue: {printer} | tipoDoc: {tipoDocumento.docPart} | user: {Request.UserHostName} | IP: {currIpAddress}");
            if (fatto)
            {
                displInfo(traduci("PrintSendOk"), true);
            }
            else
            {
                displError(traduci("PrintSendKo"), true);
            }
            raiseEvent();
        }


        /// <summary>
        /// Mostra errore ed effettua reset vari...
        /// </summary>
        /// <param name="infoMessage"></param>
        /// <param name="resetAll"></param>
        protected void displInfo(string infoMessage, bool resetAll)
        {
            lblSuccessMsg.Text = infoMessage;
            divError.Visible = false;
            divInfo.Visible = true;
            resetDisplay(resetAll);
        }
        /// <summary>
        /// Mostra errore ed effettua reset vari...
        /// </summary>
        /// <param name="errorMessage"></param>
        /// <param name="resetAll"></param>
        protected void displError(string errorMessage, bool resetAll)
        {
            lblErrorMsg.Text = errorMessage;
            divError.Visible = true;
            divInfo.Visible = false;
            resetDisplay(resetAll);
        }
        /// <summary>
        /// Reset visualizzazione
        /// </summary>
        /// <param name="resetAll">nasconde TUTTO</param>
        protected void resetDisplay(bool resetAll)
        {
            if (resetAll)
            {
                divError.Visible = false;
                divInfo.Visible = false;
                divItemDet.Visible = false;
                // elimino item sel...
                itemIdSelected = 0;
            }
            resetShowData();
        }
        /// <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;
                itemIdSelected = itemRow.ItemID;
            }
        }

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

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

        private void doUpdate()
        {
            fixVisibility();
        }

        private void fixVisibility()
        {
        }

        protected void lbtCancel_Click(object sender, EventArgs e)
        {
            resetDisplay(true);
            showItemDetail(false, null, false);
        }
    }
}