#include <stdlib.h>

#include <epicsString.h>
#include <epicsExport.h>
#include <epicsPrint.h>
#include <epicsThread.h>
#include <epicsExit.h>
#include <cantProceed.h>
#include <iocsh.h>

#include "gmdDebugStream.h"
#include "debugStream.h"
#include "ATCACommon.h"
#include "gmdBSA.h"
#include "gmdBLD.h"
#include "preamp.h"

static int gmdStreamThread(void *u)
{
    usrPvt_t *usrPvt =  (usrPvt_t*) u;
    GmdDebugStream *p = (GmdDebugStream *) usrPvt->pDrv;
    while(!usrPvt->stopLoop) {
        p->streamPoll(((usrPvt_t *)usrPvt)->ch);
    }

    epicsEventSignal(usrPvt->shutdownEvent);
    return 0;
}

extern "C" {

int gmdDebugStreamConfigure(const char *portName)
{
    drvNode_t *pList = last_drvList_ATCACommon();
    unsigned size = 0x4000;
    const char *header = "header_enabled";
    debugStreamNode_t *pStream = (debugStreamNode_t *) mallocMustSucceed(sizeof(debugStreamNode_t), "DebugStream Driver");
    pStream->portName =  epicsStrDup(portName);
    // GMD uses only one stream
    /*BPM_B_Stream referes to AMC1 will be directed to stream 0 of the Stream API*/
    pStream->streamNames[0] = epicsStrDup("BPM_B_Stream");
    pStream->streamNames[1] = epicsStrDup("");
    pStream->streamNames[2] = epicsStrDup("");
    pStream->streamNames[3] = epicsStrDup("");
    pStream->pDrv = new GmdDebugStream(pStream->portName,
                                      (pList && pList->named_root)?pList->named_root: NULL,
                                      size,
                                      (!strcmp(header, "header_enabled"))?true:false,
                                      pStream->streamNames[0],
                                      pStream->streamNames[1],
                                      pStream->streamNames[2],
                                      pStream->streamNames[3]);
    if(!pList->pdbStream0) {
        pList->pdbStream0 = pStream;
        createStreamThreads(pList->pdbStream0, gmdStreamThread);
    }
    else if (!pList->pdbStream1) {
        pList->pdbStream1 = pStream;
        createStreamThreads(pList->pdbStream1, gmdStreamThread);
    }
    else {   /* exception, two stream sub-driver instances are already launched */
    }

    return 0;
}

int gmdBsaConfigure(const char* portName, const char* photonEnChannelName,
                    const char* posXChannelName, const char* posYChannelName)
{
    DebugStreamAsynDriver* pDrv;

    if (searchDebugStreamDriver(portName, &pDrv)) {
        if (! pDrv->hasHeader()) {
            errlogPrintf("BSA information comes from the GMD stream sent by the firmware. %s was configured without header, so the BSA driver is not going to be started.\n", portName);

            return -1;
        }
        errlogPrintf("Driver %s was not initialized. The BSA is not going to be started.\n", portName);

        return -2;
    }

    class GmdBSA* gmdBSA;
    gmdBSA = GmdBSA::getInstance();
    gmdBSA->initialize(portName, photonEnChannelName, posXChannelName, posYChannelName);
    
    return 0;
}

int gmdBldConfigure(const char* portName, int bldClientId)
{
    DebugStreamAsynDriver* pDrv;

    if (searchDebugStreamDriver(portName, &pDrv)) {
        if (! pDrv->hasHeader()) {
            errlogPrintf("BLD information comes from the GMD stream sent by the firmware. %s was configured without header, so the BLD driver is not going to be started.\n", portName);

            return -1;
        }
        errlogPrintf("Driver %s was not initialized. The BLD is not going to be started.\n", portName);

        return -2;
    }
    
    class GmdBLD* gmdBLD;
    gmdBLD = GmdBLD::getInstance();
    gmdBLD->initialize(portName, bldClientId);
    
    return 0;
}

int gmdPreampConfigure(const char* portName)
{
    // Create singleton object with asyn port driver to access the pre-amp
    PreAmp::getInstance(portName);
    
    return 0;
}

} /* extern C */

/* epics ioc shell command to configure the stream processing from the firmware */
static const iocshArg   streamConfigArg0 = {"portName", iocshArgString};
static const iocshArg   *const streamConfigArgs[] = {&streamConfigArg0};
static const iocshFuncDef streamConfigFuncDef = {"gmdDebugStreamConfigure", 1, streamConfigArgs};

static void streamConfigCallFunc(const iocshArgBuf *args)
{
    gmdDebugStreamConfigure(args[0].sval);
}

/* epics ioc shell command to configure the thread that push data to the BSA Core */
static const iocshArg   gmdBsaArg0 = {"Stream Port Name", iocshArgString};
static const iocshArg   gmdBsaArg1 = {"PhotonEn BSA ch name", iocshArgString};
static const iocshArg   gmdBsaArg2 = {"PosX BSA ch name (optional)", iocshArgString};
static const iocshArg   gmdBsaArg3 = {"PosY BSA ch name (optional)", iocshArgString};
static const iocshArg   *const gmdBsaArgs[] = {&gmdBsaArg0,
                                               &gmdBsaArg1,
                                               &gmdBsaArg2,
                                               &gmdBsaArg3};
static const iocshFuncDef gmdBsaFuncDef = {"gmdBsaConfigure", 4, gmdBsaArgs};

static void gmdBsaCallFunc(const iocshArgBuf *args)
{
    gmdBsaConfigure(args[0].sval,
                    args[1].sval,
                    args[2].sval,
                    args[3].sval);
}

/* epics ioc shell command to configure the thread that push data to BLD */
static const iocshArg   gmdBldArg0 = {"Stream Port Name", iocshArgString};
static const iocshArg   gmdBldArg1 = {"BLD client ID", iocshArgInt};
static const iocshArg   *const gmdBldArgs[] = {&gmdBldArg0,
                                               &gmdBldArg1};
static const iocshFuncDef gmdBldFuncDef = {"gmdBldConfigure", 2, gmdBldArgs};

static void gmdBldCallFunc(const iocshArgBuf *args)
{
    gmdBldConfigure(args[0].sval,
                    args[1].ival);
}

/* epics ioc shell command to configure the pre-amplifier Asyn driver  */
static const iocshArg   gmdPreampArg0 = {"Preamp Port Name", iocshArgString};
static const iocshArg   *const gmdPreampArgs[] = {&gmdPreampArg0};
static const iocshFuncDef gmdPreampFuncDef = {"gmdPreampConfigure", 1, gmdPreampArgs};

static void gmdPreampCallFunc(const iocshArgBuf *args)
{
    gmdPreampConfigure(args[0].sval);
}

static void gmdShellFunctionsRegister(void)
{
    iocshRegister(&streamConfigFuncDef, streamConfigCallFunc);
    iocshRegister(&gmdBsaFuncDef, gmdBsaCallFunc);
    iocshRegister(&gmdBldFuncDef, gmdBldCallFunc);
    iocshRegister(&gmdPreampFuncDef, gmdPreampCallFunc);
}


epicsExportRegistrar(gmdShellFunctionsRegister);
