#include <stdio.h>

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

const uint8_t fsqvbl_CommandHandlerTriggerPolarity = 1;        // TRIGger:POLARity
const uint8_t fsqvbl_CommandHandlerTriggerCounter = 2;         // TRIGger:COUNTer

// -----
// @argTokens, @argTypes
// Declare argument parser entities
// Supported arguments: 1=CHARACTER
DECLARE_SCPI_ARGS_C( eScpiArg_Character );

// Argument 1 Character Values allowed list / ACM Switch State
DECLARE_ARGUMENT_CHARACTER_ALLOWED_LIST_EXPORT( MemTable_AllowedValues_TriggerState,
   "POSitive", 
   "NEGative"
);

#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_CommandHandlerSwitchState
// State's virtual table

static void fsqe_CommandHandlerTriggerState( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static void fsql_CommandHandlerTriggerState( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static const struct fFSeqEntry_t * fsqf_CommandHandlerTriggerState( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx, const struct fFSeqEntry_t * * pDeferredNext );

const fFSeqVTable_t fsqvbl_CommandHandlerTRIGgerSTATe_group = 
{
     .f = fsqf_CommandHandlerTriggerState,
     .enter = fsqe_CommandHandlerTriggerState,  
     .leave = fsql_CommandHandlerTriggerState
};

static void fsqe_CommandHandlerTriggerState( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx )
{
    sProcessProgramDataCommonContext_t * common_ctx = ctx;
    
    SCPI_PARSE_ARGUMENTS( common_ctx ); (void)common_ctx->argsParserStatus; // status is modified

    common_ctx->SwitchState.idx = 0;
    common_ctx->SwitchState.state = 0;
}

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

static const struct fFSeqEntry_t * fsqf_CommandHandlerTriggerState( 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_CommandHandlerTriggerPolarity )
               {
                // process first argument (switch state)
                common_ctx->SwitchState.state = SCPI_PROCESS_ARGUMENT_CHARACTER( common_ctx, MemTable_AllowedValues_TriggerState, 0);
               }
               
               // check result
               if( SCPI_ARGUMENT_CHARACTER_INVALID_ID == common_ctx->SwitchState.state )
               {
                   (void)common_ctx->status; // eProgramDataIllegalArgument
               }
               else
               {
                   size_t error = 0;
                   
                   if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTriggerPolarity )
                   {
                     if( common_ctx->SwitchState.state == eTrigState_Rising || common_ctx->SwitchState.state == eTrigState_Falling )
                     {
                         ControlHandle.TriggerPolaritySet(common_ctx->SwitchState.state);
                     }
                     else
                     {
                         error = 1; // Trigger state Syntax Error
                     }
                   }

                   switch( error )
                   {
                       case 1: // Trigger state Syntax Error
                       {
                           (void)common_ctx->status; // eProgramDataIllegalArgument
                       }
                       break;

//                       case 2: // Trigger State unavailable in this device
//                       {
//                           (void)common_ctx->status; // eProgramDataIllegalArgument
//                       }
//                       break;
                   }

                   if( 0 != error ) break;

                   common_ctx->status = eProgramDataDone;  // request processed, wait for reading...
               }
            }
            else
            {
               common_ctx->status = eProgramDataNeedRead;  // request processed, wait for reading...
            }
        }
        break;

        case eProgramData_Event_Read:
        {
             // @idx - current position of the source data to be outputed
             if( common_ctx->SwitchState.idx == 0 ) // first reading
             {
               size_t length = 0;
               if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTriggerPolarity )
               {
                 uint8_t triggerPolarity = ControlHandle.TriggerPolarityGet();
                 length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", triggerPolarity ? "NEGative\n" : "POSitive\n");
               }
               else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTriggerCounter )
               {
                   uint8_t triggerCount = ControlHandle.TriggerCounterGet();
                   length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%d", triggerCount);
               }

                 if( length == 0 )
                 {
                     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;
                 }
                 else
                 {
                     // place null-terminator in the end of line
                     common_ctx->tempBuffer[length] = '\0';
                 }
             }

             // 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->SwitchState.idx );
        }
        break;
    }

    return nextstate;
}
