using IOB_UT_NEXT;
using IOB_UT_NEXT.Config;
using MapoSDK;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace IOB_WIN_SIEMENS.IobSiemens
{
    /// <summary>
    /// Controllo Siemens specifico x impianti RobotSerice (es Smerigliature DONATI)
    /// </summary>
    public class SiemensRobotService : Siemens
    {
        /* --------------------------------------------------------------------------------
         * Controlli SIEMENS RobotService
         * - basasto su SIEMENS
         * - S7 vers 1500
         *
         * STRUTTURA MEMORIA DB15: (lettura) 10byte,
         * G:\Drive condivisi\30_Clienti\Donati\Schemi IOB-WIN\RobotService
         *
         *
         * DB15
         * B0.0         Num     PowerOn
         * B0.1         Num     Run
         * B0.2         Num     Contapezzi
         * B0.3         Num     Allarme
         * B0.4         Num     Manuale
         * B0.5         Num     MagOutPieno
         * B0.6         Num     MagInVuoto
         * B0.7         Num     EmergenzaArmata (0=triggered,premuta)
         * Contapezzi   DInt	2
         * PezziRiman   DInt	6
         *
         *
         * STRUTTURA MEMORIA DB14: (scrittura) 520byte,
         * G:\Drive condivisi\30_Clienti\Donati\Schemi IOB-WIN\RobotService
         *
         *
         * DB14
         * Commessa Odl	String[000..256]    String (254)
         * CodArt	    String[256..512]    String (254)
         * QtaRich      DInt        512     numero pezzi lanciati
         * PzCountRes   Bool/Byte	516     al fronte di salita (0-->1) reset contapezzi e NON CONTA mentre è 1, se 0 conta
         *
         * -------------------------------------------------------------------------------- */

        #region Public Constructors

        /// <summary>
        /// Classe base con i metodi x Siemens
        /// </summary>
        /// <param name="caller">Form chiamante</param>
        /// <param name="IOBConf">Configurazione (legacy)</param>
        /// <param name="IobConfFull">Configurazione (v 4.x)</param>
        public SiemensRobotService(AdapterFormNext caller, IobConfTree IobConfFull) : base(caller, IobConfFull)
        {
            lgInfo("NEW IOB SIEMENS versione RobotService");

            if (IOBConfFull.OptPar.ContainsKey("EMERGENCY_BYPASS"))
            {
                bool.TryParse(IOBConfFull.OptPar["EMERGENCY_BYPASS"], out EmergencyBypass);
                lgInfo($"Override EmergencyBypass da conf: {IOBConfFull.OptPar["EMERGENCY_BYPASS"]} --> {EmergencyBypass}");
            }
        }

        #endregion Public Constructors

        #region Public Methods

        /// <summary>
        /// Processo i task richiesti e li elimino dalla coda 1:1
        /// </summary>
        /// <param name="task2exe"></param>
        public override Dictionary<string, string> executeTasks(Dictionary<string, string> task2exe, string codTav)
        {
            lgInfo($"Chiamata executeTasks specifica IobSiemensRobotService: {task2exe.Count} task ricevuti");
            // Verificare il protocollo: dovrebeb togliere SOLO i task eseguiti...
            Dictionary<string, string> taskDone = new Dictionary<string, string>();
            bool taskOk = false;
            string taskVal = "";
            // inizio con 1 byte di default
            byte[] MemBlock = new byte[1];
            string memAddrWrite = "";
            if (task2exe != null)
            {
                // cerco task specifici
                foreach (var item in task2exe)
                {
                    taskOk = false;
                    taskVal = "";
                    // converto richiesta in enum...
                    taskType tName = taskType.nihil;
                    Enum.TryParse(item.Key, out tName);
                    // controllo sulla KEY
                    switch (tName)
                    {
                        case taskType.nihil:
                        case taskType.fixStopSetup:
                        case taskType.forceSetPzCount:
                        case taskType.setProg:
                        case taskType.sendWatchDogMes2Plc:
                            taskVal = $"taskReq: {tName} | key: {item.Key} | val: {item.Value} | SKIPPED | NO EXEC";
                            break;

                        case taskType.setPzComm:
                        case taskType.setArt:
                        case taskType.setComm:
                            upsertKey(item.Key, item.Value);
                            int byteSize = 0;
                            // recupero dati da memMap... altrimenti NULLA
                            if (memMap.mMapWrite.ContainsKey(item.Key))
                            {
                                dataConf currMem = memMap.mMapWrite[item.Key];
                                byteSize = currMem.size;
                                memAddrWrite = currMem.memAddr;
                                MemBlock = new byte[byteSize];
                                if (currMem.tipoMem == plcDataType.String)
                                {
                                    saveStringOnMemBlock(ref MemBlock, item.Key, 0, byteSize);
                                }
                                else if (currMem.tipoMem == plcDataType.DInt)
                                {
                                    int valDInt = 0;
                                    int.TryParse(item.Value, out valDInt);
                                    MemBlock = S7.Net.Types.DInt.ToByteArray(valDInt);
                                }
                                else if (currMem.tipoMem == plcDataType.Int)
                                {
                                    short valInt = 0;
                                    short.TryParse(item.Value, out valInt);
                                    MemBlock = S7.Net.Types.Int.ToByteArray(valInt);
                                }
                            }
                            else
                            {
                                string rawMemConf = JsonConvert.SerializeObject(memMap, Formatting.Indented);
                                lgError($"Errore: non trovata chiave write in memMap.mMapWrite per {item.Key}{Environment.NewLine}Configurazione memoria R/W:{Environment.NewLine}{rawMemConf}");
                            }
                            taskVal = item.Value;
                            break;

                        case taskType.forceResetPzCount:
                            // processo scrittura BIT su DB6.DBB516
                            MemBlock = new byte[1];
                            MemBlock = S7.Net.Types.Byte.ToByteArray(1);
                            memAddrWrite = "DB14.DBB516";
                            break;

                        case taskType.startSetup:
                            // processo scrittura BIT su DB6.DBB516
                            MemBlock = new byte[1];
                            MemBlock = S7.Net.Types.Byte.ToByteArray(1);
                            memAddrWrite = "DB14.DBB516";
                            break;

                        case taskType.stopSetup:
                            // processo scrittura BIT su DB6.DBB516
                            MemBlock = new byte[1];
                            MemBlock = S7.Net.Types.Byte.ToByteArray(0);
                            memAddrWrite = "DB14.DBB516";
                            break;

                        case taskType.setParameter:
                            // richiedo da URL i parametri WRITE da popolare
                            lgInfo("setParameter --> processMemWriteRequests");
                            taskVal = processMemWriteRequests();
                            // se restituiscce "" faccio altra prova...
                            if (string.IsNullOrEmpty(taskVal))
                            {
                                // i parametri me li aspetto come stringa composta paramName|paramvalue
                                if (item.Value.Contains("|"))
                                {
                                    string[] paramsJob = item.Value.Split('|');
                                    taskVal = $"REQUEST SET PARAMETERS: {paramsJob[0]} --> {paramsJob[1]}";
                                }
                                else
                                {
                                    taskVal = $"WRONG REQUEST FOR SET PARAMETERS: {item.Value} doesnt contain pipe for splitting key/value";
                                }
                            }
                            break;

                        default:
                            taskVal = "SKIPPED | NO EXEC";
                            break;
                    }

                    lgInfo($"executeTask | task name: {tName} | task value: {taskVal}");
                    // aggiungo task!
                    taskDone.Add(item.Key, taskVal);
                    if (!string.IsNullOrEmpty(memAddrWrite))
                    {
                        // scrivo!
                        taskOk = S7WriteBB(ref MemBlock, memAddrWrite);
                    }
                    if (taskOk)
                    {
                        // aggiorno valore memoria... SE presente
                        if (memMap.mMapWrite.ContainsKey(item.Key))
                        {
                            memMap.mMapWrite[item.Key].value = item.Value;
                            lgInfo($"Aggiornato valore in mMapWrite per {item.Key}");
                        }
                        lgInfo($"Eseguita con successo S7WriteBB per executeTasks: {item.Key} | {item.Value}");
                    }
                    else
                    {
                        lgError($"Errore in S7WriteBB durante executeTasks: {item.Key} | {item.Value}");
                    }
                }
            }
            return taskDone;
        }

        #endregion Public Methods

        #region Protected Fields

        protected bool EmergencyBypass = false;

        #endregion Protected Fields

        #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
             * B0: POWER_ON
             * B1: RUN
             * B2: pzCount
             * B3: allarme
             * B4: manuale
             * B5: MagOutPieno
             * B6: MagInVuoto
             * B7: Emergenza armata (1)
             *
             ----------------------------------------------------- */

            byte mainData = RawInput[0];

            // copio il primo byte
            int byteSignals = RawInput[0];
            // bit 0 (poweron) imposto a 1 SE connected...
            if (currPLC.IsConnected)
            {
                byteSignals |= (1 << 0);
            }
            else
            {
                byteSignals &= ~(1 << 0);
            }

            // se bypass emergenza attivo --> forzo a ARMED...
            if (EmergencyBypass)
            {
                byteSignals |= (1 << 7);
            }

            // salvo!
            B_input = byteSignals;

            // log opzionale!
            if (verboseLog)
            {
                lgInfo($"Trasformazione dati: B0: {mainData} --> B_input: {B_input}");
            }
        }

        #endregion Protected Methods
    }
}