/**
 * @file JASDNRTStateMachineGAM.cpp
 * @brief Source file for class JASDNRTStateMachineGAM
 * @date Nov 26, 2018
 * @author aneto
 *
 * @copyright Copyright 2015 F4E | European Joint Undertaking for ITER and
 * the Development of Fusion Energy ('Fusion for Energy').
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved
 * by the European Commission - subsequent versions of the EUPL (the "Licence")
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
 *
 * @warning Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an "AS IS"
 * basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the Licence permissions and limitations under the Licence.

 * @details This source file contains the definition of all the methods for
 * the class JASDNRTStateMachineGAM (public, protected, and private). Be aware that some
 * methods, such as those inline could be defined on the header file, instead.
 */

/*---------------------------------------------------------------------------*/
/*                         Standard header includes                          */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/*                         Project header includes                           */
/*---------------------------------------------------------------------------*/

#include "JASDNRTStateMachineGAM.h"

#include "AdvancedErrorManagement.h"

/*---------------------------------------------------------------------------*/
/*                           Static definitions                              */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/*                           Method definitions                              */
/*---------------------------------------------------------------------------*/

JASDNRTStateMachineGAM::JASDNRTStateMachineGAM() {
    currentState = WaitTrigger; // Set Entry state.
    plcOnTime = 0;              // Triggered time holder.
    sdnTriggerTime = 0;
    //Output and condition in a given state.
    conditionTrigger = 1;
    aps_hvon = 0;
    aps_swon = 0;
    bps_hvon = 0;
    bps_swon = 0;
    mhvps_hvon = 0;

    // Parameters which get from Input signals.
    triggerSignal = NULL_PTR(MARTe::uint32 *);
    currentTime = NULL_PTR(MARTe::uint32 *);
    triggerDelay_mhvps_hvon = NULL_PTR(MARTe::uint32 *);
    triggerDelay_aps_hvon = NULL_PTR(MARTe::uint32 *);
    triggerDelay_aps_swon = NULL_PTR(MARTe::uint32 *);
    triggerDelay_bps_hvon = NULL_PTR(MARTe::uint32 *);
    triggerDelay_bps_swon = NULL_PTR(MARTe::uint32 *);
    triggerDelay_shotlen = NULL_PTR(MARTe::uint32 *);
    stopRequest = NULL_PTR(MARTe::uint32 *);
    modePulseLengthLimit = NULL_PTR(MARTe::uint32 *);
    sdnCommand = NULL_PTR(MARTe::uint16 *);

    // write out target.
    outputSignal = NULL_PTR(MARTe::uint32 *);
    outputBeamON = NULL_PTR(MARTe::uint32 *);
    outputHVArmed = NULL_PTR(MARTe::uint32 *);
    outputHVInjection = NULL_PTR(MARTe::uint32 *);
    outputRFON = NULL_PTR(MARTe::uint32 *);
    outputBeamONTime = NULL_PTR(MARTe::uint32 *);
    outputRFONTime = NULL_PTR(MARTe::uint32 *);
    shotCounter = NULL_PTR(MARTe::uint32 *);

    mhvps_hvon_is_on = false;
    aps_hvon_is_on = false;
    aps_swon_is_on = false;
    bps_hvon_is_on = false;
    bps_swon_is_on = false;
}

JASDNRTStateMachineGAM::~JASDNRTStateMachineGAM() {
}

bool JASDNRTStateMachineGAM::Initialise(MARTe::StructuredDataI & data) {
    using namespace MARTe;
    bool ok = GAM::Initialise(data);
    if (ok) {
        ok = data.Read("ConditionTrigger", conditionTrigger);
        if (!ok) {
            REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "The Condition1 shall be specified");
        }
    }
    if (ok) {
        ok = data.Read("mhvps_hvon", mhvps_hvon);
        if (!ok) {
            REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "The mhvps_hvon shall be specified");
        }
    }
    if (ok) {
        ok = data.Read("aps_hvon", aps_hvon);
        if (!ok) {
            REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "The aps_hvon shall be specified");
        }
    }
    if (ok) {
        ok = data.Read("aps_swon", aps_swon);
        if (!ok) {
            REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "The aps_swon shall be specified");
        }
    }
    if (ok) {
        ok = data.Read("bps_hvon", bps_hvon);
        if (!ok) {
            REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "The bps_hvon shall be specified");
        }
    }
    if (ok) {
        ok = data.Read("bps_swon", bps_swon);
        if (!ok) {
            REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "The bps_swon shall be specified");
        }
    }
    return ok;
}

bool JASDNRTStateMachineGAM::PrepareNextState(const MARTe::char8 * const currentStateName, const MARTe::char8 * const nextStateName) {

    return true;
}

bool JASDNRTStateMachineGAM::Setup() {
    using namespace MARTe;
    bool ok = (numberOfInputSignals == 11u);
    if (ok) {
        ok = (numberOfOutputSignals == 8u);
        if (!ok) {
            REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "Seven output signals shall be defined");
        }
    }
    else {
        REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "Nine input signals shall be defined");
    }
    if (ok) {
        uint32 c;
        for (c = 0u; c < numberOfInputSignals; c++) {
            TypeDescriptor inputType = GetSignalType(InputSignals, c);
            ok = (inputType == UnsignedInteger32Bit || inputType == UnsignedInteger16Bit);
            if (!ok) {
                StreamString signalName;
                (void) GetSignalName(InputSignals, c, signalName);
                REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "Signal %s shall be defined as uint32 or uint16", signalName.Buffer());
            }

        }
    }
    if (ok) {
        uint32 c;
        for (c = 0u; c < numberOfOutputSignals; c++) {
            TypeDescriptor outputType = GetSignalType(OutputSignals, c);
            ok = (outputType == UnsignedInteger32Bit);
            if (!ok) {
                StreamString signalName;
                (void) GetSignalName(InputSignals, c, signalName);
                REPORT_ERROR(MARTe::ErrorManagement::ParametersError, "Signal %s shall be defined as uint32", signalName.Buffer());
            }
        }
    }
    if (ok) {
        currentTime = reinterpret_cast<uint32 *>(GetInputSignalMemory(0));
        triggerSignal = reinterpret_cast<uint32 *>(GetInputSignalMemory(1));
        triggerDelay_mhvps_hvon = reinterpret_cast<uint32 *>(GetInputSignalMemory(2));
        triggerDelay_aps_hvon = reinterpret_cast<uint32 *>(GetInputSignalMemory(3));
        triggerDelay_aps_swon = reinterpret_cast<uint32 *>(GetInputSignalMemory(4));
        triggerDelay_bps_hvon = reinterpret_cast<uint32 *>(GetInputSignalMemory(5));
        triggerDelay_bps_swon = reinterpret_cast<uint32 *>(GetInputSignalMemory(6));
        triggerDelay_shotlen = reinterpret_cast<uint32 *>(GetInputSignalMemory(7));
        stopRequest = reinterpret_cast<uint32 *>(GetInputSignalMemory(8));
        modePulseLengthLimit = reinterpret_cast<uint32 *>(GetInputSignalMemory(9));
        sdnCommand = reinterpret_cast<uint16 *>(GetInputSignalMemory(10));

        outputSignal = reinterpret_cast<uint32 *>(GetOutputSignalMemory(0));
        outputBeamON = reinterpret_cast<uint32 *>(GetOutputSignalMemory(1));
        outputHVArmed = reinterpret_cast<uint32 *>(GetOutputSignalMemory(2));
        outputHVInjection = reinterpret_cast<uint32 *>(GetOutputSignalMemory(3));
        outputRFON = reinterpret_cast<uint32 *>(GetOutputSignalMemory(4));
        outputBeamONTime = reinterpret_cast<uint32 *>(GetOutputSignalMemory(5));
        outputRFONTime  = reinterpret_cast<uint32 *>(GetOutputSignalMemory(6));
        shotCounter = reinterpret_cast<uint32 *>(GetOutputSignalMemory(7));
        *shotCounter = 0;
    }
    return ok;
}

bool JASDNRTStateMachineGAM::Execute() {
    using namespace MARTe;
    if (currentState == WaitTrigger) {

        //State Transition condition
        if ((*triggerSignal == conditionTrigger)) {
            REPORT_ERROR(ErrorManagement::Debug, "Start beam-on sequence in SDN mode.");
            plcOnTime = *currentTime; //Save pulse start time.
            *outputBeamON = 0;
            //State transition.
            currentState = SwitchingHVPS_HVON;
        }
    }
    else if (currentState == SwitchingHVPS_HVON) {

        //Actions in this state.
    	if (*stopRequest != 0 || *triggerSignal != conditionTrigger) {
    		*outputSignal -= aps_swon;
    		currentState = HVTerminate;
    	}
        if (*currentTime >= (plcOnTime + *triggerDelay_bps_hvon) && bps_hvon_is_on == false){
            //Do action
            *outputSignal += bps_hvon;
            bps_hvon_is_on = true;
            REPORT_ERROR(ErrorManagement::Debug, "bps_hvon was set to outputSignal at %d.", *currentTime);
        }
        if (*currentTime >= (plcOnTime + *triggerDelay_aps_hvon) && aps_hvon_is_on == false) {
            //Do action
            *outputSignal += aps_hvon;
            aps_hvon_is_on = true;
            REPORT_ERROR(ErrorManagement::Debug, "aps_hvon was set to outputSignal.");
        }

        *outputBeamONTime = *currentTime - plcOnTime; //Save RFON start time.
        if (bps_hvon_is_on && aps_hvon_is_on){
            *outputHVArmed = 0;
            currentState = WaitSDNTrigger;
        }

    }
    else if (currentState == WaitSDNTrigger) {

        // Action in this state
        *outputBeamONTime = *currentTime - plcOnTime; //Save RFON start time.

        // State change conditions
        if (*sdnCommand == 1){
            sdnTriggerTime = *currentTime;
            currentState = SwitchingHVPS_SWON;
        }
        if (*stopRequest != 0 || *triggerSignal != conditionTrigger) {
            *outputSignal = 0;
            currentState = HVTerminate;
        }
    }
    else if (currentState == SwitchingHVPS_SWON) {

        //Actions in this state.
        if (*stopRequest != 0 || *triggerSignal != conditionTrigger) {
            *outputSignal = 0;
            currentState = HVTerminate;
        }

        if (*currentTime >= (sdnTriggerTime + *triggerDelay_bps_swon) && bps_swon_is_on==false){
            //Do action
            *outputSignal += bps_swon;
            bps_swon_is_on = true;
            REPORT_ERROR(ErrorManagement::Debug, "bps_swon was set to outputSignal at %d.", *currentTime);
        }
        if (*currentTime >= (sdnTriggerTime + *triggerDelay_mhvps_hvon) && mhvps_hvon_is_on==false) {
            //Do action
            *outputSignal += mhvps_hvon;
            mhvps_hvon_is_on = true;
            REPORT_ERROR(ErrorManagement::Debug, "mhvps_hvon was set to outputSignal at %d.", *currentTime);
        }
        if (bps_swon_is_on && mhvps_hvon_is_on && *currentTime >= (sdnTriggerTime + *triggerDelay_aps_swon)){
            //Do action
            *outputSignal += aps_swon;
            aps_swon_is_on = true;
            apsSwonTime = *currentTime;
            REPORT_ERROR(ErrorManagement::Debug, "aps_swon was set to outputSignal at %d.", *currentTime);
        }
        *outputBeamONTime = *currentTime - plcOnTime; //Save RFON start time.

        if (bps_swon_is_on || mhvps_hvon_is_on){
            *outputHVInjection = 0;
        }

        //State transition condition
        if (aps_swon_is_on){
            currentState = RFON;
            *outputRFON = 0;
            *shotCounter += 1;
            REPORT_ERROR(ErrorManagement::Debug, "state was changed to RFON");
        }
    }
    else if (currentState == RFON) {

        //SDN command processing.
        if (*sdnCommand == 4 && aps_swon_is_on) {
            *outputSignal -= aps_swon;
            aps_swon_is_on = false;
            REPORT_ERROR(ErrorManagement::Debug, "sdn command was 4");
        }
        if (*sdnCommand == 3 && !aps_swon_is_on) {
            *outputSignal += aps_swon;
            aps_swon_is_on = true;
            REPORT_ERROR(ErrorManagement::Debug, "sdn command was 3");
        }

        //Action in this state.
        if ((*sdnCommand == 2) || (*modePulseLengthLimit == 1u) || (*currentTime >= (sdnTriggerTime + *triggerDelay_aps_swon + *triggerDelay_shotlen))) {
        	REPORT_ERROR(ErrorManagement::Debug, "shotlen: %d", *triggerDelay_shotlen);
            if (*sdnCommand == 2) {
                REPORT_ERROR(ErrorManagement::Information, "sdn command was 2");
            } else if (*currentTime >= (sdnTriggerTime + *triggerDelay_aps_swon + *triggerDelay_shotlen)){
                REPORT_ERROR(ErrorManagement::Information, "pulse length reached setpoint.");
            }
            //Do action
            *outputSignal -= aps_swon; //Turn off only aps_swon
            mhvps_hvon_is_on = false;
            aps_hvon_is_on = false;
            aps_swon_is_on = false;
            bps_hvon_is_on = false;
            bps_swon_is_on = false;
            REPORT_ERROR(ErrorManagement::Debug, "0 was set to outputSignal at %d.", *currentTime);
        }
        *outputRFON = 0;
        *outputBeamONTime = *currentTime - plcOnTime;
        *outputRFONTime = *currentTime - apsSwonTime;


        //State transition condition
        if (!aps_swon_is_on && !bps_swon_is_on && !mhvps_hvon_is_on) {
            currentState = HVTerminate;
            apsSwoffTime = *currentTime;
            REPORT_ERROR(ErrorManagement::Information, "state was changed to HVTerminate");
        }
    }
    else if (currentState == HVTerminate) {

        //Action in this state.
        *outputBeamON = 1;
        *outputHVArmed = 1;
        *outputHVInjection = 1;
        *outputRFON = 1;

        // State transition condition.
        if (*currentTime - apsSwoffTime >= turn_off_delay){
            *outputSignal = 0;
        }
        if (*triggerSignal == false){ 
            //Check PLC_ON is reset
            currentState = WaitTrigger;
            *outputSignal = 0;
            REPORT_ERROR(ErrorManagement::Debug, "state was changed to WaitTrigger");
        }
    }

    return true;
}

CLASS_REGISTER(JASDNRTStateMachineGAM, "1.0")
