#include <stdio.h>

#define SCPI_ARGS_N_C 2
#define SCPI_ARGS_N_Q 0
#include "app/scpi/scpi_handler.h"
#include "app/control_table/control_table.h"

// -----
// @argTypesCommand
// Declare argument parser entities for command form
// Supported arguments: 1=NUMERIC
DECLARE_SCPI_ARGS_C( eScpiArg_Numeric, eScpiArg_Numeric );
// -----
// @argTypesQuery
// Declare argument parser entities for query form
// Supported arguments: 0
DECLARE_SCPI_ARGS_Q();

DECLARE_ARGUMENT_NUMERIC_VALUES_I32(AllowedValues_PortNumber, 0, 16);

const uint8_t fsqvbl_CommandHandlerPortSet    = 1;  // CTRL:PORT
const uint8_t fsqvbl_CommandHandlerMeasStart  = 2;  // MEAS:START
const uint8_t fsqvbl_CommandHandlerMeasStop   = 3;  // MEAS:STOP
const uint8_t fsqvbl_CommandHandlerMeasCont   = 4;  // MEAS:CONTinue
const uint8_t fsqvbl_CommandHandlerMeasMode   = 5;  // MEAS:MODE

#include "app/scpi/commandHandlers/power_switch.h"
#include "app/nfm/nfm_base.h"

// Refer to:
// [1] SCPI Specification, revision 1999.0
//     "Standard Commands for Programmable Instruments (SCPI), VERSION 1999.0, May 1999"
// [2] Gpib Programming Tutorial, (http://g2pc1.bu.edu/~qzpeng/gpib/manual/GpibProgTut.pdf)
//     Electronics Group (http://www.few.vu.nl/~elec), 11 January 2000 Electronics Group
// [3] IEEE 488.2 Standard, revision IEEE Std 488.2-1987 (1992)
//     "IEEE Standard Codes, Formats, Protocols, and Common Commands for Use With IEEE Std 488.1-1987, IEEE

// =================================================================================
// @fsqvbl_CommandHandlerMEASnSWITCH_group
// State's virtual table

static void fsqe_CommandHandlerCtrl_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static void fsql_CommandHandlerCtrl_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static const struct fFSeqEntry_t * fsqf_CommandHandlerCtrl_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx, const struct fFSeqEntry_t * * pDeferredNext );

const fFSeqVTable_t fsqvbl_CommandHandlerCtrl_group = 
{
     .f = fsqf_CommandHandlerCtrl_Switch_Group,
     .enter = fsqe_CommandHandlerCtrl_Switch_Group,  
     .leave = fsql_CommandHandlerCtrl_Switch_Group
};

static void fsqe_CommandHandlerCtrl_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx )
{
    sProcessProgramDataCommonContext_t * common_ctx = ctx;
    
    common_ctx->MeasAndSwitch.idx = 0;
    
    SCPI_PARSE_ARGUMENTS( common_ctx ); (void)common_ctx->argsParserStatus; // status is modified
}

static void fsql_CommandHandlerCtrl_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx )
{
}

static const struct fFSeqEntry_t * fsqf_CommandHandlerCtrl_Switch_Group( const struct fFSeqEntry_t * this, 
                                                                         tFSeqCtx_t ctx, 
                                                                          const struct fFSeqEntry_t * * pDeferredNext )
{
    const fFSeqEntry_t * nextstate = NULL;
    
    sProcessProgramDataCommonContext_t * common_ctx = ctx;
    sScpiParserContext_t * global_ctx = common_ctx->global_ctx;

    switch( common_ctx->event )
    {
        case eProgramData_Event_Write:
        {
            if( eScpiStatus_success != common_ctx->argsParserStatus ) // check argument parser status
            {
               common_ctx->status = eProgramDataArgumentSyntax;  // parameter syntax error, caller should generate error message
            }
            else if( ! common_ctx->isQuery )
            {
               common_ctx->status = eProgramDataIllegalArgument;  // forward set, illegal parameter value, caller should generate error message
               if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerPortSet )
               {
                    // Parse first argument
                    const sNumericEntry_t * ne = SCPI_PROCESS_ARGUMENT_NUMERIC(common_ctx, &AllowedValues_PortNumber, 0);
                    if( ScpiNumericSuccess != ne->error ) break;
                    uint16_t port1 = ne->Value.demicalInteger;
                    
                    // Parse second argument
                    ne = SCPI_PROCESS_ARGUMENT_NUMERIC(common_ctx, &AllowedValues_PortNumber, 1);
                    if( ScpiNumericSuccess != ne->error ) break;
                    uint16_t port2 = ne->Value.demicalInteger;
                    
                    if((port1 || port2) && (port1 == port2)) break;
                    
                    if( port1 > NFMClass->properties.allowedOutputPorts || port2 > NFMClass->properties.allowedOutputPorts)
                    {
                        common_ctx->status = eProgramDataRuntimeError;
                        break;
                    }

                    if( !NFMClass->methods.portMethods.setPortState(eNFMPort_1, port1) || !NFMClass->methods.portMethods.setPortState(eNFMPort_2, port2) )
                    {
                        common_ctx->status = eProgramDataRuntimeError;
                        break;
                    }
                    
                    sTableTablePoint_t portCommutation = 
                    {
                        .port1 = NFMClass->methods.portMethods.getPortState(eNFMPort_1),
                        .port2 = NFMClass->methods.portMethods.getPortState(eNFMPort_2)
                    };
                    
                    ControlHandle.PortSet(portCommutation);
                    
                    common_ctx->status = eProgramDataDone;
               }
            }
            else
            {
                 common_ctx->status = eProgramDataNeedRead;  // request processed, wait for reading...
                 (void)nextstate; // stay in this state
            }
        }
        break;

        case eProgramData_Event_Read:
        {
             // @idx - current position of the source data to be outputed
             if( common_ctx->MeasAndSwitch.idx == 0 ) // first reading
             {
                 size_t length = 0;                 
                 if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerPortSet )
                 {
                     sTableTablePoint_t portState = ControlHandle.PortRead();
                     NFMClass->methods.portMethods.setPortState(eNFMPort_1, portState.port1);
                     NFMClass->methods.portMethods.setPortState(eNFMPort_2, portState.port2);
                     length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%d, %d", portState.port1, portState.port2);
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMeasStart )
                 {
                     ControlHandle.Start_Meas();
                     length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", "OK\n");
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMeasStop )
                 {
                     ControlHandle.Stop_Meas();
                     length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", "OK\n");
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMeasCont )
                 {
                     ControlHandle.Continue_Meas();
                     length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", "OK\n");
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMeasMode )
                 {
                     uint8_t res = ControlHandle.Mode_Meas();
                     if(res != ERROR_CODE)
                     {
                         length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", res ? "TABLE\n" : "MANUAL\n");
                     }
                 }
				 
                 if( length > 0 )
                 {
                     // place null-terminator in the end of line
                     common_ctx->tempBuffer[length] = '\0';
                 }
                 else
                 {
                     
                     fsq_RaiseError( SCPI_ERROR_INTERNAL_DEVICE,
                                     SCPI_ERROR_INTERNAL_DEVICE_MSG,
                                     global_ctx->sParser.xHandlerToken.shead,
                                     global_ctx->sParser.xHandlerToken.stail );

                     common_ctx->status = eProgramData_SpecificError; // specific error already generated
                     break;
                 }
             }

             // Since @done flag is set, this dispatcher shall not be called anymore.
             // Since this handler is implemented as a single-state automat, there no
             // ... other states to go to:
             (void)nextstate;

             // modify current postion index:
             SCPI_RESPONSE_HELPER( common_ctx, common_ctx->MeasAndSwitch.idx );
        }
        break;
    }

    return nextstate;
}
