#include <stdio.h>

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

const uint8_t fsqvbl_CommandHandlerMeasurementInternalTemperature = 1; // MEASurement:TEMPerature:INTernal
const uint8_t fsqvbl_CommandHandlerMeasurementExternalTemperature = 2; // MEASurement:TEMPerature:EXTernal
const uint8_t fsqvbl_CommandHandlerMeasurementTempCoefficient     = 3; // MEASurement:TEMPerature:TCOEfficient
const uint8_t fsqvbl_CommandHandlerAmpSwitchCount = 4;                 // GAIN:COUNt
const uint8_t fsqvbl_CommandHandlerAmpSwitchList = 5;                  // GAIN:LIST
const uint8_t fsqvbl_CommandHandlerFiltSwitchCount = 6;                // FILT:COUNT
const uint8_t fsqvbl_CommandHandlerFiltSwitchList = 7;                 // FILT:LIST

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

DECLARE_ARGUMENT_NUMERIC_VALUES_I32(AllowedValues_BCoefficient, 0, 9999);

#include "app/scpi/commandHandlers/measurement_and_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_CommandHandlerMeasurement_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static void fsql_CommandHandlerMeasurement_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static const struct fFSeqEntry_t * fsqf_CommandHandlerMeasurement_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx, const struct fFSeqEntry_t * * pDeferredNext );

const fFSeqVTable_t fsqvbl_CommandHandlerMEASnSWITCH_group = 
{
     .f = fsqf_CommandHandlerMeasurement_Switch_Group,
     .enter = fsqe_CommandHandlerMeasurement_Switch_Group,  
     .leave = fsql_CommandHandlerMeasurement_Switch_Group
};

static void fsqe_CommandHandlerMeasurement_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_CommandHandlerMeasurement_Switch_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx )
{
}

static const struct fFSeqEntry_t * fsqf_CommandHandlerMeasurement_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_CommandHandlerMeasurementTempCoefficient )
               {
                    const sNumericEntry_t * ne = SCPI_PROCESS_ARGUMENT_NUMERIC(common_ctx, &AllowedValues_BCoefficient, 0);
        
                    if( NULL != ne )
                    switch( ne->error )
                    {
                        case ScpiNumericSuccess:
                        {
                            NFMClass->methods.tempCoefficient.setTempCoeff(ne->Value.demicalInteger);
                            
                            common_ctx->status = eProgramDataDone;
                        }
                        break;
                
                        // -------- processed by SCPI_PROCESS_ARGUMENT_NUMERIC ----
                        // "11.5.1.1.5", [3]
                        // "10.10.6 Error Handling", [3]
                        // "<...> An out-of-range integer shall cause an Execution Error, see 11.5.1.1.5. <...>"
                        case ScpiNumericError_DEVICE_RANGE:   // the value is out of range supported by device
                        case ScpiNumericError_USER_RANGE:     // the value is out of user specified range:   // the value is out of range supported by device
                        case ScpiNumericError_USER_TYPE:      // the value does not match to the user expectation
                        case ScpiNumericInvalidArg:           // forbidden case: design bug                      
                        case ScpiNumericError:                // generic numeric conversion error
                        break;
                        // --------------------------------------------------------
                    }
               }
            }
            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_CommandHandlerMeasurementInternalTemperature )
                 {
                     float temp = NFMClass->methods.getAverageTemperature();

                     length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%.3f", temp); 
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMeasurementExternalTemperature )
                 {
                     float temp = NFMClass->methods.getAverageExtTemperature();
                     
                     length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%.3f", temp); 
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMeasurementTempCoefficient )
                 {
                     uint16_t temp_coeff = 0;
                     NFMClass->methods.tempCoefficient.getTempCoeff(&temp_coeff);

                     length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%d", temp_coeff ); 
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerAmpSwitchCount )
                 {
                     length = 0;//_snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%d", NFMClass->properties.allowedAmpStatesCount );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerAmpSwitchList )
                 {
                     length = NFMClass->methods.getAmpStateList( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer) );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerFiltSwitchCount )
                 {
                     length = 0; //_snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%d", NFMClass->properties.allowedFiltStatesCount );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerFiltSwitchList )
                 {
                     length = NFMClass->methods.getFilterStateList( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer) );
                 }

                 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;
}
