#include <stdio.h>

#define SCPI_ARGS_N 1
#define SCPI_ARGS_MANDATORY_N 0
#include "app/scpi/scpi_handler.h"

const uint8_t fsqvbl_CommandHandlerMemoryTableAnalyzer = 1;        // MEMory:TABLe:ANALyzer
const uint8_t fsqvbl_CommandHandlerMemoryTableDate = 2;            // MEMory:TABLe:DATE
const uint8_t fsqvbl_CommandHandlerMemoryTableOperator = 3;        // MEMory:TABLe:OPERator
const uint8_t fsqvbl_CommandHandlerMemoryTablePlace = 4;           // MEMory:TABLe:PLACe
const uint8_t fsqvbl_CommandHandlerMemoryTablePoints = 5;          // MEMory:TABLe:POINts
const uint8_t fsqvbl_CommandHandlerMemoryTableTemperature = 6;     // MEMory:TABLe:TEMPerature
const uint8_t fsqvbl_CommandHandlerMemoryTableTime = 7;            // MEMory:TABLe:TIME
const uint8_t fsqvbl_CommandHandlerMemoryTableFrequencyStart = 8;  // MEMory:TABLe:FREQuency:STARt
const uint8_t fsqvbl_CommandHandlerMemoryTableFrequencyStop = 9;   // MEMory:TABLe:FREQuency:STOP
const uint8_t fsqvbl_CommandHandlerMemoryTableFrequencyType = 10;  // MEMory:TABLe:FREQuency:TYPE

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

// Argument 1 Character Values allowed list / Memory Bank
DECLARE_ARGUMENT_CHARACTER_ALLOWED_LIST_IMPORT( MemTable_AllowedValues_Bank )

#include "app/scpi/commandHandlers/memory_table_group.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_CommandHandlerMemoryTableAnalyzer
// State's virtual table

static void fsqe_CommandHandlerMemoryTable_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static void fsql_CommandHandlerMemoryTable_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static const struct fFSeqEntry_t * fsqf_CommandHandlerMemoryTable_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx, const struct fFSeqEntry_t * * pDeferredNext );

const fFSeqVTable_t fsqvbl_CommandHandlerMEMoryTABLe_group = 
{
     .f = fsqf_CommandHandlerMemoryTable_Group,
     .enter = fsqe_CommandHandlerMemoryTable_Group,  
     .leave = fsql_CommandHandlerMemoryTable_Group
};

static void fsqe_CommandHandlerMemoryTable_Group( 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->MemTableCommon.idx = 0;
    common_ctx->MemTableCommon.bank = 0;
    common_ctx->MemTableCommon.port = 0;
}

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

static const struct fFSeqEntry_t * fsqf_CommandHandlerMemoryTable_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( ! common_ctx->isQuery )
            {
               common_ctx->status = eProgramDataSyntaxError; // invalid command header type: COMMAND not supported
            }
            else if( eScpiStatus_success != common_ctx->argsParserStatus ) // check argument parser status
            {
               common_ctx->status = eProgramDataArgumentSyntax;  // parameter syntax error, caller should generate error message
            }
            else
            {
               common_ctx->status = eProgramDataIllegalArgument;  // forward set, illegal parameter value, caller should generate error message

               // check count of arguments
               if( common_ctx->args > 0 )
               {
                   // process first argument (bank)
                   common_ctx->MemTableCommon.bank = SCPI_PROCESS_ARGUMENT_CHARACTER( common_ctx, MemTable_AllowedValues_Bank, 0 );
               }
               else
               {
                   // first argument (bank)
                   common_ctx->MemTableCommon.bank = 0; // FACTORY (default)
               }
               
               // check result
               if( SCPI_ARGUMENT_CHARACTER_INVALID_ID != common_ctx->MemTableCommon.bank )
               {
                   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->MemTableCommon.idx == 0 ) // first reading
             {
                 eChrz_t bank = (eChrz_t)((eChFactory) + common_ctx->MemTableCommon.bank); 
                 size_t length = 0;
                 bool number = false;
                 bool rc = false;

                 if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableAnalyzer )
                 {
                     rc = NFMClass->methods.xCharacterization.getAnalyzer( bank,
                                                                           common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer),
                                                                           &length );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableDate )
                 {
                     rc = NFMClass->methods.xCharacterization.getDate( bank,
                                                                       common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer),
                                                                       &length );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableOperator )
                 {
                     rc = NFMClass->methods.xCharacterization.getOperator( bank,
                                                                           common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer),
                                                                           &length );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTablePlace )
                 {
                     rc = NFMClass->methods.xCharacterization.getPlace( bank,
                                                                        common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer),
                                                                        &length );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTablePoints )
                 {
                     int16_t points = 0; number = true;
                     rc = NFMClass->methods.xCharacterization.getPointsCountSafe( bank, &points );

                     if( rc ) length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%d", points );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableTemperature )
                 {
                     double temp = 0.0; number = true;
                     rc = NFMClass->methods.xCharacterization.getChrzTemp( bank, &temp );

                     if( rc ) length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%.4f", temp );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableTime )
                 {
                     rc = NFMClass->methods.xCharacterization.getTime( bank,
                                                                       common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer),
                                                                       &length );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableFrequencyStart )
                 {
                     double freq = 0.0; number = true;
                     rc = NFMClass->methods.xCharacterization.getStartFreq( bank, &freq );

                     if( rc ) length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%1.8E", freq );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableFrequencyStop )
                 {
                     double freq = 0.0; number = true;
                     rc = NFMClass->methods.xCharacterization.getStopFreq( bank, &freq );

                     if( rc ) length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%1.8E", freq );
                 }
                 else if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerMemoryTableFrequencyType )
                 {
                     eChrzScaleType_t type = eChScale_undefined;
                     rc = NFMClass->methods.xCharacterization.getScaleType( bank, &type );

                     if( rc )
                     {
                         switch( type )
                         {
                            case eChScaleLinear:
                            length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", "LIN" );
                            break;
                            case eChScaleSegment:
                            length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", "SEGM" );
                            break;
                            default: rc = false;
                         }
                     }
                 }

                 if( rc )
                 {
                     if( length == 0 )
                     {
                         if( number )
                         {
                         common_ctx->tempBuffer[0] = '0';
                         length = 1;
                         }
                         else
                         {
                         common_ctx->tempBuffer[0] = '\'';
                         common_ctx->tempBuffer[1] = ' ';
                         common_ctx->tempBuffer[2] = '\'';
                         length = 3;
                         }
                     }
                     // place null-terminator in the end of line
                     common_ctx->tempBuffer[length] = '\0';
                 }
                 else
                 {
                     // Formal call: in case the parameter is optional, the token is unfilled.
                     // So it is required to fill the token with correct values from allowed list.
                     SCPI_ARGUMENT_CHARACTER_VALUE_TOKEN( MemTable_AllowedValues_Bank,
                                                          common_ctx->MemTableCommon.bank,
                                                          &common_ctx->argTokens[0] );

                     fsq_RaiseErrorEx( SCPI_ERROR_CHRZ_DATA_NOTFOUND,
                                       SCPI_ERROR_CHRZ_DATA_NOTFOUND_MSG,
                                       common_ctx->argTokens[0].shead,
                                       common_ctx->argTokens[0].stail,
                                       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->MemTableCommon.idx );
        }
        break;
    }

    return nextstate;
}
