using AppData;
using Newtonsoft.Json;
using SteamWare;
using System;
using System.Collections.Generic;

namespace NKC_WF
{
    public class BaseUserControl : System.Web.UI.UserControl
    {
        #region Protected Fields

        /// <summary>
        /// Membro gestione accessi al datalayer (istanza x ogni classe controllo)
        /// </summary>
        protected DataLayer DLMan = new DataLayer();

        #endregion Protected Fields

        #region Public Fields

        /// <summary>
        /// Codice macchina (da v2)
        /// </summary>
        public string PlaceCod = "WRK001";

        #endregion Public Fields

        #region Public Events

        /// <summary>
        /// Generico evento di richiesta refresh a aprent
        /// </summary>
        public event EventHandler eh_doRefresh;

        /// <summary>
        /// Generico evento di richiesta refresh a aprent
        /// </summary>
        public event EventHandler eh_doReset;

        #endregion Public Events

        #region Protected Properties

        protected Dictionary<int, string> anagMateriali
        {
            set
            {
                string jsonData = JsonConvert.SerializeObject(value);
                memLayer.ML.setRSV("anagMateriali", jsonData, 60);
            }
            get
            {
                Dictionary<int, string> answ = new Dictionary<int, string>();
                //cerco in redis...
                string rawData = memLayer.ML.getRSV("anagMateriali");
                if (!string.IsNullOrEmpty(rawData))
                {
                    answ = JsonConvert.DeserializeObject<Dictionary<int, string>>(rawData);
                }
                // sennò nel DB e salvo in redis...
                else
                {
                    var tabMat = DLMan.taMat.GetData();
                    foreach (var item in tabMat)
                    {
                        answ.Add(item.MatID, item.MatDesc);
                    }
                    // salvo in redis
                    anagMateriali = answ;
                }
                // restituisco
                return answ;
            }
        }

        #endregion Protected Properties

        #region Public Properties

        /// <summary>
        /// verifica sia ambiente PROD (vs DEV)
        /// </summary>
        public bool checkProd
        {
            get
            {
                return memLayer.ML.CRS("environment") == "PROD";
            }
        }

        /// <summary>
        /// Recupera IP utente
        /// </summary>
        /// <returns></returns>
        public string currIpAddress
        {
            get
            {
                string userip = Request.UserHostAddress;
                return userip;
            }
        }

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        /// determina CSS x colore testo da perc svuotamento...
        /// </summary>
        /// <param name="ratio"></param>
        /// <returns></returns>
        public string getCssByRatio(double ratio)
        {
            string answ = "text-dark";
            if (ratio == 0)
            {
                answ = "text-danger";
            }
            else if (ratio == 1)
            {
                answ = "text-success";
            }
            else
            {
                answ = "text-warning";
            }
            return answ;
        }

        /// <summary>
        /// Restituisce URL immagine QRCode
        /// </summary>
        /// <param name="QrValue">Parametro da renderizzare con QRCode</param>
        /// <returns></returns>
        public string getImgUrl(object QrValue)
        {
            string baseUrl = $"{memLayer.ML.CRS("matrixUrl")}/HOME/QR_site/JSON?val=";
            string payload = "{'baseUrl':'{0}','parameters':['" + $"{QrValue}" + "']}";
            string answ = $"{baseUrl}{payload}";
            return answ;
        }

        /// <summary>
        /// Recupera valore intero da OBJ
        /// </summary>
        /// <param name="_val"></param>
        /// <returns></returns>
        public double getInt(object _val)
        {
            int answ = -999999;
            int.TryParse(_val.ToString(), out answ);
            return answ;
        }

        /// <summary>
        /// Calcola il rapporto tra 2 valori
        /// </summary>
        /// <param name="_dividendo"></param>
        /// <param name="_divisore"></param>
        /// <returns></returns>
        public double getRatio(object _dividendo, object _divisore)
        {
            double ratio = 0;
            double dividendo = 0;
            double divisore = 1;
            double.TryParse(_dividendo.ToString(), out dividendo);
            double.TryParse(_divisore.ToString(), out divisore);
            // se divisore 0 --> 1
            divisore = divisore == 0 ? 1 : divisore;
            ratio = dividendo / divisore;
            return ratio;
        }

        /// <summary>
        /// Wrapper scrittura log DEBUG
        /// </summary>
        /// <param name="message"></param>
        public void lgDebug(string message)
        {
            logger.lg.scriviLog(message, tipoLog.DEBUG);
        }

        /// <summary>
        /// Wrapper scrittura log ERROR
        /// </summary>
        /// <param name="message"></param>
        public void lgError(string message)
        {
            logger.lg.scriviLog(message, tipoLog.ERROR);
        }

        /// <summary>
        /// Wrapper scrittura log EXCEPTION
        /// </summary>
        /// <param name="message"></param>
        public void lgException(string message, Exception exc)
        {
            logger.lg.scriviLog($"{message}{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
        }

        /// <summary>
        /// Wrapper scrittura log FATAL
        /// </summary>
        /// <param name="message"></param>
        public void lgFatal(string message, Exception exc)
        {
            logger.lg.scriviLog(message, tipoLog.FATAL);
        }

        /// <summary>
        /// Wrapper scrittura log INFO
        /// </summary>
        /// <param name="message"></param>
        public void lgInfo(string message)
        {
            logger.lg.scriviLog(message, tipoLog.INFO);
        }

        public string matByKey(object _matId)
        {
            string answ = "";
            int matId = 0;
            int.TryParse(_matId.ToString(), out matId);
            try
            {
                answ = anagMateriali[matId];
            }
            catch
            { }
            return answ;
        }

        /// <summary>
        /// Converte obja intero
        /// </summary>
        /// <param name="valore"></param>
        /// <returns></returns>
        public int obj2int(object valore)
        {
            int answ = 0;
            int.TryParse(valore.ToString(), out answ);
            return answ;
        }

        /// <summary>
        /// Chiamata evento
        /// </summary>
        public void raiseEvent()
        {
            // se qualcuno ascolta sollevo evento nuovo valore...
            if (eh_doRefresh != null)
            {
                eh_doRefresh(this, new EventArgs());
            }
        }

        /// <summary>
        /// Chiamata evento
        /// </summary>
        public void raiseReset()
        {
            // se qualcuno ascolta sollevo evento nuovo valore...
            if (eh_doReset != null)
            {
                eh_doReset(this, new EventArgs());
            }
        }

        /// <summary>
        /// Wrapper traduzione termini
        /// </summary>
        /// <param name="lemma"></param>
        /// <returns></returns>
        public string traduci(string lemma)
        {
            return SteamWare.user_std.UtSn.Traduci(lemma);
        }

        #endregion Public Methods
    }
}