#include <stdio.h>

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

const uint8_t fsqvbl_CommandHandlerTableMatrixAddPoints    = 1;  // TABle:ADD
const uint8_t fsqvbl_CommandHandlerTableMatrixClear        = 2;  // TABle:CLR
const uint8_t fsqvbl_CommandHandlerTableMatrixDone         = 3;  // TABle:DONE
const uint8_t fsqvbl_CommandHandlerTableMatrixEdit         = 4;  // TABle:EDIT
const uint8_t fsqvbl_CommandHandlerTableMatrixGet          = 5;  // TABle:GET

// -----
// @argTokens, @argTypes
// Declare argument parser entities
// Supported arguments: ARRAY_ARG=ARRAY
DECLARE_SCPI_ARGS( eScpiArg_Array_Decimal );

// Arguments Decimal Values allowed
DECLARE_ARGUMENT_NUMERIC_VALUES_I32(AllowedValues_TableNumbers, 0, 9999);

#include "app/scpi/commandHandlers/scpi_table.h"
#include "app/control_table/control_table.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 size_t printValues( char * pcBuffer, size_t szBuffer, const sSWTablePoint_t * pValues, size_t nValues, bool theLastOne );
static void fsqe_CommandHandlerTable_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static void fsql_CommandHandlerTable_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static const struct fFSeqEntry_t * fsqf_CommandHandlerTable_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx, const struct fFSeqEntry_t * * pDeferredNext );

const fFSeqVTable_t fsqvbl_CommandHandlerTable_group = 
{
     .f = fsqf_CommandHandlerTable_Group,
     .enter = fsqe_CommandHandlerTable_Group,  
     .leave = fsql_CommandHandlerTable_Group
};

static void fsqe_CommandHandlerTable_Group( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx )
{
    sProcessProgramDataCommonContext_t * common_ctx = ctx;
    
    common_ctx->MeasAndSwitch.idx = 0;
    
    SCPI_PARSE_ARRAY_ARGUMENTS( common_ctx ); (void)common_ctx->argsParserStatus; // status is modified
    
    common_ctx->MemTablePlanData.idx = 0;
    common_ctx->MemTablePlanData.nchs = 0;
    common_ctx->MemTablePlanData.bank = 0;    
    common_ctx->MemTablePlanData.init = false;
    common_ctx->MemTablePlanData.isdone = false;

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

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

static const struct fFSeqEntry_t * fsqf_CommandHandlerTable_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_CommandHandlerTableMatrixAddPoints )
               {
                   
                   if(!TableHandle.AddPoints(common_ctx->argArray, common_ctx->args))
                   {
                       common_ctx->status = eProgramDataSyntaxError;
                       break;
                   }
                   common_ctx->status = eProgramDataDone;
                   break;
                   
               }
               if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTableMatrixClear )
               {
                   if(TableHandle.ClearTable())
                   {
                       common_ctx->status = eProgramDataDone;
                       break;
                   }
               }
               if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTableMatrixDone )
               {
                  TableHandle.SetEditState(false); // set table done
                  common_ctx->status = eProgramDataDone;
                  break;
               }
               if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTableMatrixEdit )
               {
                  TableHandle.SetEditState(true); // set table undone
                  common_ctx->status = eProgramDataDone;
                  break;
               }
            }
            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->MeasAndSwitch.idx == 0 ) // first reading
             {
                 size_t length = 0;
                 //common_ctx->SwitchState.state = SCPI_PROCESS_ARGUMENT_ARRAY(common_ctx, &AllowedValues_TableNumbers, 0);
                 if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTableMatrixDone )
                 {
                    const char * temp = !TableHandle.GetEditState() ? "YES\n" : "NO\n"; // get table state done?
                    length = _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "%s", temp);
                 }
                 if( common_ctx->handler_ctx == &fsqvbl_CommandHandlerTableMatrixGet )
                 {
                     do
                     {
                        // @idx - current position of the source data to be outputed
                        if( common_ctx->MemTablePlanData.idx >= common_ctx->MemTablePlanData.nchs )
                        {
                            if( common_ctx->MemTablePlanData.isdone ) break;
    
                            // There no already prepared data in @tempBuffer
                            if( ! common_ctx->MemTablePlanData.init ) // first reading
                            {
                                eChunks_t chrz = (eChunks_t)((eChValues) + common_ctx->MemTablePlanData.bank);
                                common_ctx->status = eProgramDataIllegalArgument; // forward set
    
                                switch( NFMClass->methods.xTable.getTablePoints_Init( chrz,
                                                                                      common_ctx->MemTablePlanData.dTablePoints,
                                                                                      cellsof(common_ctx->MemTablePlanData.dTablePoints),
                                                                                      &common_ctx->MemTablePlanData.getctx ) )
                                {                                                     
                                    case eNFMGetPointError_Success:
                                        common_ctx->MemTablePlanData.init = true;
                                    break;
    
                                    case eNFMGetPointError_DataError: 
                                        goto L_TableSegment_DATAERR;
    
                                    case eNFMGetPointError_InvalidValue:
                                    default:                         
                                        goto L_TableSegment_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.dTablePoints
                            // are interconnected. Number of cells @MemTablePlanData.dTablePoints 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 @dTablePoints):
                            //STATIC_ASSERT( (sizeof(common_ctx->tempBuffer) / PRINT_VALUE_MIN_SPACE) == cellsof(common_ctx->MemTablePlanData.dTablePoints), "Invalid size" );
                            // Greater (there is unused cells in @dTablePoints):
                            STATIC_ASSERT( (sizeof(common_ctx->tempBuffer) / PRINT_VALUE_MIN_SPACE) <= cellsof(common_ctx->MemTablePlanData.dTablePoints), "Invalid size" );
    
                            size_t nPointsRetrieve = sizeof(common_ctx->tempBuffer) / PRINT_VALUE_MIN_SPACE;
                            switch( NFMClass->methods.xTable.getTablePoints_Next( &common_ctx->MemTablePlanData.getctx,
                                                                                 &nPointsRetrieve) )
                            {
                                case eNFMGetPointError_Success:       common_ctx->MemTablePlanData.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->MemTablePlanData.dTablePoints, nPointsRetrieve, common_ctx->MemTablePlanData.isdone );                          
                                    }
    
                                    common_ctx->tempBuffer[ l ] = '\0';
    
                                    common_ctx->MemTablePlanData.idx = 0;  // reset prepared characters index
                                    common_ctx->MemTablePlanData.nchs = l; // prepared characters in buffer
                                }
                                break;
                                case eNFMGetPointError_DataError:     goto L_TableSegment_DATAERR;
                                case eNFMGetPointError_InvalidValue:  
                                default:                             goto L_TableSegment_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->MemTablePlanData.idx, common_ctx->MemTablePlanData.isdone );

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

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

                     SCPI_RESPONSE_HELPER_EXTDONE_SET( common_ctx, bufferEmpty && common_ctx->MemTablePlanData.isdone );
                     break;
                 }
                 				 
                 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;
    
    L_TableSegment_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->MemTablePlanData.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_TableSegment_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 sSWTablePoint_t * 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), "%d-%d", pValues->port1, pValues->port2 );
            else
            l = _snprintf( &pcBuffer[idx], (szBuffer-idx), "%d-%d%c%c", pValues->port1, pValues->port2, ',' , ' ' );
            pValues++;
        }

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

        idx += l;
        nValues--;
    }

    return idx;
}