using IOB_UT_NEXT;
using IOB_UT_NEXT.Config;
using System;

namespace IOB_WIN_MBUS.IobModbusTCP
{
    /* --------------------------------------------------------------------------------
    * Controlli ModBusTCP Rimor
    * - protocollo ModBus TCP
    * - specifico comportamento sabbiatura e ossitaglio x IMI Remosa
    * - gestione stato
    * - gestione allarmi
    * - gestione parametri (ore/minuti funzionamento)
    *
    * G:\Drive condivisi\30_Clienti\IMI-Remosa\Richieste nuove integrazioni\RIMOR
    *
    * -------------------------------------------------------------------------------- */

    public class ModbusTCPRimor : ModbusTCP
    {
        #region Public Constructors

        /// <summary>
        /// Classe base con i metodi x ModBusTCP
        /// </summary>
        /// <param name="caller">Form chiamante</param>
        /// <param name="IOBConf">Configurazione (legacy)</param>
        /// <param name="IobConfFull">Configurazione (v 4.x)</param>
        public ModbusTCPRimor(AdapterFormNext caller, IobConfTree IobConfFull) : base(caller, IobConfFull)
        {
            lgInfo("NEW IOB ModBus TCP Rimor");

            // provo lettura una prima volta i dati DYN
            if (currPLC != null && currPLC.Connected)
            {
                try
                {
                    processDynData();
                    if (EnableTest)
                    {
                        ProcessDataSync();
                        testReadExt();
                    }
                }
                catch (Exception exc)
                {
                    lgError($"Eccezione in processDynData iniziale x ModBus TCP Rimor:{Environment.NewLine}{exc}");
                }
            }
        }

        #endregion Public Constructors

        #region Protected Properties

        /// <summary>
        /// Restituisce controllo IN ALLARME
        /// </summary>
        protected bool AlarmState
        {
            get
            {
                bool answ = false;
                if (memMap.OptMemPar.ContainsKey("AlarmBitCond"))
                {
                    answ = testDisInBitCondition("AlarmBitCond");
                }
                else if (memMap.OptMemPar.ContainsKey("AlarmIntCond"))
                {
                    answ = testIntCondition("AlarmIntCond");
                }
                return answ;
            }
        }

        /// <summary>
        /// Restituisce status di END ORDINE (chiusura ODL se aperto) HARD coded
        /// </summary>
        protected bool EndOrderState
        {
            get
            {
                bool answ = false;
                if (memMap.OptMemPar.ContainsKey("EndOrdBitCond"))
                {
                    answ = testDisInBitCondition("EndOrdBitCond");
                }
                else if (memMap.OptMemPar.ContainsKey("EndOrdIntCond"))
                {
                    answ = testIntCondition("EndOrdIntCond");
                }
                return answ;
            }
        }

        /// <summary>
        /// Restituisce status di ESTOP triggered (triggered = premuta, altrimenti armed)
        /// </summary>
        protected bool EStopTriggered
        {
            get
            {
                bool answ = false;
                if (memMap.OptMemPar.ContainsKey("EStopBitCond"))
                {
                    answ = testDisInBitCondition("EStopBitCond");
                }
                else if (memMap.OptMemPar.ContainsKey("EStopIntCond"))
                {
                    answ = testIntCondition("EStopIntCond");
                }
                return answ;
            }
        }

        /// <summary>
        /// Restituisce status di Manuale, hard coded
        /// </summary>
        protected bool ManualState
        {
            get
            {
                bool answ = false;
                if (memMap.OptMemPar.ContainsKey("ManualBitCond"))
                {
                    answ = testDisInBitCondition("ManualBitCond");
                }
                else if (memMap.OptMemPar.ContainsKey("ManualIntCond"))
                {
                    answ = testIntCondition("ManualIntCond");
                }
                return answ;
            }
        }

        /// <summary>
        /// Restituisce status di WORK (auto + lavora), hard coded
        /// </summary>
        protected bool WorkState
        {
            get
            {
                bool answ = false;
                if (memMap.OptMemPar.ContainsKey("WorkBitCond"))
                {
                    answ = testDisInBitCondition("WorkBitCond");
                }
                else if (memMap.OptMemPar.ContainsKey("WorkIntCond"))
                {
                    answ = testIntCondition("WorkIntCond");
                }
                return answ;
            }
        }

        #endregion Protected Properties

        #region Protected Methods

        /// <summary>
        /// Effettua decodifica aree memoria alla bitmap usata x MAPO
        /// </summary>
        protected override void decodeToBaseBitmap()
        {
            // init a zero...
            B_input = 0;

            /* -----------------------------------------------------
             * bitmap MAPO STANDARD 60
             * B0: POWER_ON
             * B1: RUN
             * B2: pzCount
             * B3: allarme
             * B4: manuale
             * B5: slowTC
             * B6: WarmUpCoolDown
             * B7: EmergArmata
             *
             ----------------------------------------------------- */

            var MemInt = new byte[2];

            int byteSignals = 0;
            // bit 0 (poweron) imposto a 1 SE connected...
            if (currPLC.Connected)
            {
                byteSignals += (1 << 0);
            }
            // se ho qualcosa nella holding register...
            if (HoldingRegisterLUT != null && HoldingRegisterLUT.Count > 0)
            {
                // se emergenza NON premuta (triggered) indico OK (armata...) FARE !!! togliere true
                //if (!EStopTriggered)
                if (true)
                {
                    byteSignals += (1 << 7);
                }

                // impiego controlli da setup IntConditions... processo dagli stati + gravi...
                if (AlarmState || hasAlarms())
                {
                    byteSignals += (1 << 3);
                }
                else if (ManualState)
                {
                    byteSignals += (1 << 4);
                }
                else if (WorkState)
                {
                    byteSignals += (1 << 1);
                }

                // controllo SE avesse ODL attivo ma fosse in condizione end ordine --> mando
                // chiusura ODL
                if (currIdxODL > 0)
                {
                    if (EndOrderState)
                    {
                        // invio chiusura ODL
                        TryCloseCurrODL();
                    }
                }
            }
            else
            {
                lgInfo("HoldingRegisterLUT vuoto!");
            }

            // salvo!
            B_input = byteSignals;
        }

        /// <summary>
        /// Effettua sync dati
        /// </summary>
        protected override void ProcessDataSync()
        {
            // richiesta check autoODL
            ProcessAutoOdl();
            // richiesta generazione quotidiana dossiers
            ProcessAutoDossier();
            // effettua gestione import file...
            ProcessFileImport();
        }

        #endregion Protected Methods
    }
}