#include <stdio.h>
#define PRINT_VALUE_MIN_SPACE (20) // DO NOT TOUCH! =20, see @printValues
#define SCPI_ARGS_N 1
#define SCPI_ARGS_MANDATORY_N 0
#include "app/scpi/scpi_handler.h"

// -----
// @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_freq_data.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_CommandHandlerMemoryTableFrequencyData
// State's virtual table

static size_t printValues( char * pcBuffer, size_t szBuffer, const double * pValues, size_t nValues, bool theLastOne );
static void fsqe_CommandHandlerMemoryTableFrequencyData( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static void fsql_CommandHandlerMemoryTableFrequencyData( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static const struct fFSeqEntry_t * fsqf_CommandHandlerMemoryTableFrequencyData( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx, const struct fFSeqEntry_t * * pDeferredNext );

const fFSeqVTable_t fsqvbl_CommandHandlerMEMoryTABLeFREQuencyDATA = 
{
     .f = fsqf_CommandHandlerMemoryTableFrequencyData,
     .enter = fsqe_CommandHandlerMemoryTableFrequencyData,  
     .leave = fsql_CommandHandlerMemoryTableFrequencyData
};

static void fsqe_CommandHandlerMemoryTableFrequencyData( 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->MemTableFreqData.idx = 0;
    common_ctx->MemTableFreqData.nchs = 0;
    common_ctx->MemTableFreqData.bank = 0;    
    common_ctx->MemTableFreqData.init = false;
    common_ctx->MemTableFreqData.isdone = false;

    memset( &common_ctx->MemTableFreqData.getctx, 0, sizeof(common_ctx->MemTableFreqData.getctx) );
}

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

static const struct fFSeqEntry_t * fsqf_CommandHandlerMemoryTableFrequencyData( 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

               if( common_ctx->args > 0 )
               // process first argument (bank)
               common_ctx->MemTableFreqData.bank = SCPI_PROCESS_ARGUMENT_CHARACTER( common_ctx, MemTable_AllowedValues_Bank, 0 );
               else
               // default parameter
               common_ctx->MemTableFreqData.bank = 0; // Factory

               // check result
               if( SCPI_ARGUMENT_CHARACTER_INVALID_ID != common_ctx->MemTableFreqData.bank )
               {
                   common_ctx->status = eProgramDataNeedRead;  // request processed, wait for reading...
               }
            }
        }
        break;

        case eProgramData_Event_Read:
        {
             do
             {

             // @idx - current position of the source data to be outputed
             if( common_ctx->MemTableFreqData.idx >= common_ctx->MemTableFreqData.nchs )
             {
                 if( common_ctx->MemTableFreqData.isdone ) break;

                 // There no already prepared data in @tempBuffer
                 if( ! common_ctx->MemTableFreqData.init ) // first reading
                 {
                     eChrz_t chrz = (eChrz_t)((eChFactory) + common_ctx->MemTableFreqData.bank); 
                     common_ctx->status = eProgramDataIllegalArgument; // forward set

                     switch( NFMClass->methods.xCharacterization.getScaleFreqs_Init( chrz, 
                                                                                     common_ctx->MemTableFreqData.dFreqPoints,
                                                                                     cellsof(common_ctx->MemTableFreqData.dFreqPoints), 
                                                                                     &common_ctx->MemTableFreqData.getctx ) )
                     {
                         case eNFMGetPointError_Success:
                              common_ctx->MemTableFreqData.init = true;
                         break;

                         case eNFMGetPointError_DataError: goto L_FrequencySegment_DATAERR;

                         case eNFMGetPointError_InvalidValue:
                         default:                         goto L_FrequencySegment_PARAMERR;
                     }
                 }
                 #if SCPI_MAX_CMD_TEMP_BUFFER < PRINT_VALUE_MIN_SPACE
                 #error Invalid value 'SCPI_MAX_CMD_TEMP_BUFFER'
                 #endif
     
                 // The length of temporary string buffer, length of one printable number and number of cells in @MemTableFreqData.dFreqPoints
                 // are interconnected. Number of cells @MemTableFreqData.dFreqPoints should be equal or be greater than maximum number of
                 // printed numbers into the @tempBuffer. But it is recommend that these numbers be equal.
                 // Equal (no unused cells in @dFreqPoints):
                 STATIC_ASSERT( (sizeof(common_ctx->tempBuffer) / PRINT_VALUE_MIN_SPACE) == cellsof(common_ctx->MemTableFreqData.dFreqPoints), "Invalid size" );
                 // Greater (there is unused cells in @dFreqPoints):
                 //STATIC_ASSERT( (sizeof(common_ctx->tempBuffer) / PRINT_VALUE_MIN_SPACE) <= cellsof(common_ctx->MemTableFreqData.dFreqPoints), "Invalid size" );

                 size_t nPointsRetrieve = sizeof(common_ctx->tempBuffer) / PRINT_VALUE_MIN_SPACE;
                 switch( NFMClass->methods.xCharacterization.getScaleFreqs_Next( &common_ctx->MemTableFreqData.getctx,
                                                                                 &nPointsRetrieve ) )
                 {
                     case eNFMGetPointError_Success:       common_ctx->MemTableFreqData.isdone = true;
                     case eNFMGetPointError_OutOfBuffer:
                     case eNFMGetPointError_Limit:
                     {
                          size_t l = 0;

                          if( nPointsRetrieve > 0 )
                          {
                              l = printValues( common_ctx->tempBuffer, sizeof( common_ctx->tempBuffer ), 
                                               common_ctx->MemTableFreqData.dFreqPoints, nPointsRetrieve, common_ctx->MemTableFreqData.isdone );                          
                          }

                          common_ctx->tempBuffer[ l ] = '\0';

                          common_ctx->MemTableFreqData.idx = 0;  // reset prepared characters index
                          common_ctx->MemTableFreqData.nchs = l; // prepared characters in buffer
                     }
                     break;
                     case eNFMGetPointError_DataError:     goto L_FrequencySegment_DATAERR;
                     case eNFMGetPointError_InvalidValue:  
                     default:                             goto L_FrequencySegment_PARAMERR;
                 }
             }

             // 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_EXTDONE_IDXINC( common_ctx, common_ctx->MemTableFreqData.idx, common_ctx->MemTableFreqData.isdone );

             }
             // While output buffer swallows all the prepared data from @tempBuffer
             while( (common_ctx->MemTableFreqData.idx >= common_ctx->MemTableFreqData.nchs) );

             bool bufferEmpty = (common_ctx->MemTableFreqData.idx >= common_ctx->MemTableFreqData.nchs);

             SCPI_RESPONSE_HELPER_EXTDONE_SET( common_ctx, bufferEmpty && common_ctx->MemTableFreqData.isdone );
        }
        break;
    }

    return nextstate;

L_FrequencySegment_DATAERR:

    // 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->MemTableFreqData.bank,
                                        &common_ctx->argTokens[0] );

    fsq_RaiseErrorEx( SCPI_ERROR_DATA_CORRUPTED,
                                       SCPI_ERROR_DATA_CORRUPTED_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
    return NULL;

L_FrequencySegment_PARAMERR:
   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
   return NULL;
}

// @printValues
// Prints an array of double numbers into the buffer.
// If there no free space in the output buffer while not all the numbers are printed, function returns 0;
// @pcBuffer - output buffer;
// @szBuffer - size of output buffer;
// @pValues - an array of numbers to print;
// @nValues - amount of numbers to print;
// @theLastOne - the last call indicator
// Returns:
// - In case all of numbers are printed: number of bytes printed into the output buffer;
// - 0 otherwise
static size_t printValues( char * pcBuffer, size_t szBuffer, const double * pValues, size_t nValues, bool theLastOne )
{
    // One point has the following format:
    // <Freq_i>,<SPACE>
    // One number has 16 symbols length plus 2 (comma and space)
    // So, 18 characters required to print one point.
    // To prevent overflowing by _snprintf() with printing null-term,
    // it is required at lease 20 characters free, see @PRINT_VALUE_MIN_SPACE

    size_t idx = 0;
    while( nValues > 0 )
    {
        size_t l = 0;

        if( (szBuffer-idx) >= PRINT_VALUE_MIN_SPACE )
        {
            if( theLastOne && (nValues==1) )
            l = _snprintf( &pcBuffer[idx], (szBuffer-idx), "%1.10e", (*pValues++) );
            else
            l = _snprintf( &pcBuffer[idx], (szBuffer-idx), "%1.10e%c%c", (*pValues++), ',' , ' ' );
        }

        if( l == 0 || l >= (szBuffer-idx) )
        {
            return 0; // insuffecient buffer
        }

        idx += l;
        nValues--;
    }

    return idx;
}
