#include <stdio.h>

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

#include "app/scpi/commandHandlers/opc.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
//      Standard Digital Interface for Programmable Instrumentation"

// =================================================================================
// @fsqvbl_CommandHandlerOPC
// State's virtual table

static void fsqe_CommandHandlerOPC( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static void fsql_CommandHandlerOPC( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx );
static const struct fFSeqEntry_t * fsqf_CommandHandlerOPC( const struct fFSeqEntry_t * this, tFSeqCtx_t ctx, const struct fFSeqEntry_t * * pDeferredNext );

const fFSeqVTable_t fsqvbl_CommandHandlerOPC = 
{
     .f = fsqf_CommandHandlerOPC,
     .enter = fsqe_CommandHandlerOPC,  
     .leave = fsql_CommandHandlerOPC
};

static void fsqe_CommandHandlerOPC( 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->OPC.idx = 0; // reset position
}

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

static const struct fFSeqEntry_t * fsqf_CommandHandlerOPC( 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 = eProgramDataNeedRead;  // request processed, wait for reading...
               (void)nextstate; // stay in this state
            } 
            else
            {
 
               // "11.2 Status Byte Register", [1]
               // "12.5.2.1.2 Operation Complete Command Active State (OCAS)", [3]
               // "4.1.3.3 *OPC and *WAI", [1]
               // Implementation of the *OPC and *WAI commands is straightforward in devices which
               // implement only sequential commands. When executing *OPC the device simply sets the OPC bit of SESR.
               GPIBMachine.fGPIB_set_event_status_register_operation_complete_state( &global_ctx->sGPIB.registers, true );

               common_ctx->status = eProgramDataDone;  // request processed
            } 
 
            // 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;
        }
        break;

        case eProgramData_Event_Read:
        {
            // first call: prepare buffer
            if( 0 == common_ctx->OPC.idx )
            {
                memset( common_ctx->tempBuffer, 0, sizeof(common_ctx->tempBuffer) );

                // "4.1.3.4 *OPC?" [1]
                // Implementation of the *OPC? query is straightforward in devices which implement only
                // sequential commands. When executing *OPC? the device simply places a “1" in the Output Queue.
                
                // "12.5.3 The *OPC? Common Query", [3]
                // The *OPC? query allows synchronization between a controller and a device using the MAV bit in the Status Byte or
                // a read of the Output Queue. Detailed illustrations of the use of this function appear in Appendix B. Note that,
                // unlike the *OPC command described in 12.5.2, the *OPC? query does not in any way affect the OPC Event bit in the
                // Standard Event Status Register (ESR).

                // Since there no asyncronious operations are supported, this command immediately generate the response "1"
                _snprintf( common_ctx->tempBuffer, sizeof(common_ctx->tempBuffer), "1" );
            }

            SCPI_RESPONSE_HELPER( common_ctx, common_ctx->OPC.idx );

            (void)nextstate; // stay in this state
        }
        break;
    }

    return nextstate;
}

