#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>

#include <string>
#include <sstream>
#include <fstream>

#include <sys/types.h>
#include <sys/stat.h>


#include <epicsTypes.h>
#include <epicsTime.h>
#include <epicsThread.h>
#include <epicsString.h>
#include <epicsTimer.h>
#include <epicsMutex.h>
#include <epicsEvent.h>
#include <epicsMutex.h>
#include <epicsPrint.h>
#include <iocsh.h>

#include <drvSup.h>
#include <epicsExport.h>
#include <registryFunction.h>

#include <asynPortDriver.h>
#include <asynOctetSyncIO.h>

#include "mrLlrfAsynDriver.h"
#include "streamDispatch.h"
#include "streamDataType.h"
#include "streamDataProc.h"
#include "mrLlrfDataProc.h"

#include "registerTimeStampSource.h"


static const char *driverName = "mrLlrfAsynDrver";
static char port_name[32];
static int once = 0;
static class mrLlrfAsynDriver *pLlrfDrv;


mrLlrfAsynDriver::mrLlrfAsynDriver(const char *portName)
    : asynPortDriver(portName,
                     1, /* number of elements of this device */
                     NUM_MRLLRF_DET_PARAMS, /* number of asyn params of be cleared for each device */
                     asynInt32Mask | asynFloat64Mask | asynOctetMask | asynDrvUserMask | asynInt16ArrayMask | asynInt32ArrayMask | asynFloat64ArrayMask, /* Interface mask */
                     asynInt32Mask | asynFloat64Mask | asynOctetMask | asynEnumMask | asynInt16ArrayMask | asynInt32ArrayMask | asynFloat64ArrayMask,  /* Interrupt mask */
                     1, /* asynFlags.  This driver does block and it is not multi-device, so flag is 1 */
                     1, /* Autoconnect */
                     0, /* Default priority */
                     0) /* Default stack size*/
{
    char stream_name[32];
  	sprintf(stream_name, "%s_%s", "mrLlrf", portName);
  	stream_subscribe_id = streamSubscribe(stream_name);
	
	  if(initChnData()) printf("malloc error for llrf stream proc\n");
    if(mrLlrfDataProc_init()) printf("malloc error for llrf data proc\n");

    paramSetup(); 

}
 
mrLlrfAsynDriver::~mrLlrfAsynDriver() {}

const char* mrLlrfAsynDriver::getDriverName(void) { return driverName; }

void mrLlrfAsynDriver::mrLlrfProcess(void *buf, unsigned timeslot)
{
    mrLlrfDataProc_collectDaq(buf, timeslot);
    mrLlrfDataProc_delayMeasure(buf, DAQ);
    
    mrLlrfDataProc_calcSignal(buf, timeslot);
    mrLlrfDataProc_delayMeasure(buf, CALC);
}

void mrLlrfAsynDriver::mrLlrfPVProcess(void *buf, unsigned timeslot)
{
    for(int i = 0; i< MAX_CHANNEL_NUMBER; i++) {
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].avg_phase, mrLlrfDataProc_getAvgPhase(i, timeslot));            // update phase for each channel
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].avg_amplitude, mrLlrfDataProc_getAvgAmplitude(i, timeslot));    // update amplitude for each channel
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].avg_power,  mrLlrfDataProc_getAvgPower(i, timeslot));           // update power for each channel
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].refsub_phase, mrLlrfDataProc_getRefSubPhase(i, timeslot));      // update reference subtracted phase for each channel
    }
 
    setDoubleParam(p_phase_firmware[ts(timeslot)], mrLlrfDataProc_getPhaseFirmware(timeslot));   
    setDoubleParam(p_phase[ts(timeslot)], mrLlrfDataProc_getPhase(timeslot));
    setDoubleParam(p_amplitude[ts(timeslot)], mrLlrfDataProc_getAmplitude(timeslot));
    setDoubleParam(p_power[ts(timeslot)], mrLlrfDataProc_getPower(timeslot));
    
    setDoubleParam(p_prev_p_corr[ts(timeslot)], mrLlrfDataProc_getPrevPCorr(timeslot));   // previous dac set vlaues need to be updated always
    setDoubleParam(p_prev_a_corr[ts(timeslot)], mrLlrfDataProc_getPrevACorr(timeslot));   // previous dac set values need to be udpated always
    
    setDoubleParam(p_p_err[ts(timeslot)], mrLlrfDataProc_getPErr(timeslot));
    
    if(1 || mrLlrfDataProc_getDacControl()) {     /* if dac control is enabled, update PVs and let them trigger DAC PVs */
        setDoubleParam(p_p_corr[ts(timeslot)], mrLlrfDataProc_getPCorr(timeslot));
        setDoubleParam(p_a_corr[ts(timeslot)], mrLlrfDataProc_getACorr(timeslot));
    }
    
    
    callParamCallbacks();
    
}

void mrLlrfAsynDriver::mrLlrfSigWfPosting(void *buf, unsigned timeslot)
{
     mrLlrf_rfData_t *pRf;
     int ts;
     
     
     if(timeslot == 4) ts = 0;
     else if(timeslot == 1) ts = 1;
     else return;
     
     for (int i = 0; i < MAX_CHANNEL_NUMBER; i++) {
         pRf = mrLlrfDataProc_getDataPointer(i, timeslot);
               
         
         // waveform post for raw RF signal
         
         doCallbacksInt16Array(pRf->raw, pRf->num_raw, p_signalWaveform[i][ts].raw, 0);
         
         // waveform post for i
         doCallbacksFloat64Array(pRf->i, pRf->num_i, p_signalWaveform[i][ts].i, 0); 
         
         // waveform post for q
         doCallbacksFloat64Array(pRf->q, pRf->num_q, p_signalWaveform[i][ts].q, 0);
         
         // waveform post for phase
         doCallbacksFloat64Array(pRf->phase, pRf->num_phase, p_signalWaveform[i][ts].phase, 0);
         
         // waveform post for amplitude
         doCallbacksFloat64Array(pRf->amplitude, pRf->num_amplitude, p_signalWaveform[i][ts].amplitude, 0);
         
         
     }
       
     mrLlrfDataProc_delayMeasure(buf, PVPOST);
     
        
}

typedef struct {
    char name[64];
} mrLlrfProcTaskArg;

void mrLlrfAsynDriver::mrLlrfProcTask(void *p)
{
    void *buf = (void*) malloc(STREAM_BUFF_SIZE);
    unsigned timeslot;
    timing_header_t *p_time_header; 
	
    while(1) {
        getStreamData(stream_subscribe_id, buf);
        timeslot = getDataFromBuffer(buf);
        if(timeslot != 4 && timeslot != 1) continue;

        p_time_header = (timing_header_t*) buf;
        time = p_time_header->time;


        updateTimeStamp();
           
        mrLlrfProcess(buf, timeslot);    
        mrLlrfPVProcess(buf, timeslot);    // real-time
        mrLlrfSigWfPosting(buf, timeslot);
        
	    
	}

}

int mrLlrfAsynDriver::ts(unsigned timeslot)
{
    if(timeslot == 4) return 0;
    if(timeslot == 1) return 1;
    
    return -1;
}


void mrLlrfAsynDriver::TimeStampSourceProcess(adTimeStampSource_p pTss, epicsTimeStamp *pTime)
{
    epicsMutexLock(pTss->lock);
    *pTime = time;
    epicsMutexUnlock(pTss->lock);
}


extern "C" {

static void printElapsedTimeMeasure(void)
{
    unsigned c, ts;
    epicsFloat64 t_current, t_min, t_max;
    
    printf("Stream Proc Delay Measurement (us)\n");
    
    for(c = 0; c < MAX_CHANNEL_NUMBER; c++) {
        ts = 4;
        elapsedTimeMeasure(c, ts, &t_current, &t_min, &t_max);
        printf("channel %2u, timeslot %u,  delay: current %4.0lf usec, min %4.0lf usec, max %4.0lf usec\n",
               c, ts, t_current, t_min, t_max);
        
        
        ts =1;
        elapsedTimeMeasure(c, ts, &t_current, &t_min, &t_max);
        printf("            timeslot %u,  delay: current %4.0lf usec, min %4.0lf usec, max %4.0lf usec\n",
               ts, t_current, t_min, t_max);
    }
}

static void printCounters(void)
{

    unsigned c, ts;
    epicsUInt32 tsErrCnt_iq, tsErrCnt_pa, tsErrCnt_raw;
    epicsUInt16 num_raw, num_i, num_q, num_phase, num_amplitude;
    
    printf("Timslot Error Counts and Sample Counters\n");
    
    for(c=0; c< MAX_CHANNEL_NUMBER; c++) {
        tsErrCounters(c, &tsErrCnt_iq, &tsErrCnt_pa, &tsErrCnt_raw);
        printf("channel %u, error counters: iq %d, pa %d, raw %d\n",
                c, tsErrCnt_iq, tsErrCnt_pa, tsErrCnt_raw);
                
        ts = 4;
        sampleCounters(c, ts, &num_raw, &num_i, &num_q, &num_phase, &num_amplitude);
        printf("            timeslot %u: raw %u, i %u, q %u, phase %u, amplitude %u\n",
               ts, num_raw, num_i, num_q, num_phase, num_amplitude);
        
        ts = 1; 
        sampleCounters(c, ts, &num_raw, &num_i, &num_q, &num_phase, &num_amplitude);
        printf("            timeslot %u: raw %u, i %u, q %u, phase %u, amplitude %u\n",
               ts, num_raw, num_i, num_q, num_phase, num_amplitude);
    }
}


static void mrLlrfTimeStampSource(void *puserPvt, epicsTimeStamp *pTime)
{
    adTimeStampSource_p  pTss = (adTimeStampSource_p) puserPvt;
    if(!pTss) return;
    
    if(pLlrfDrv) pLlrfDrv->TimeStampSourceProcess(pTss, pTime);

}

epicsRegisterFunction(mrLlrfTimeStampSource);


static void mrLlrfProcTask(void *p)
{
    if(pLlrfDrv) pLlrfDrv->mrLlrfProcTask(p);

}


static int mrLlrfAsynDriverConfigure(const char *portName) 
{
    
    pLlrfDrv = new mrLlrfAsynDriver(portName);

    strcpy(port_name, portName);


    return 0;
}



/* epics ioc shell command */

static const iocshArg initArg0 = { "port name", iocshArgString };
static const iocshArg * const initArgs[] = { &initArg0 };
static const iocshFuncDef initFuncDef = {"mrLlrfConfigure", 1, initArgs };
static void initCallFunc(const iocshArgBuf * args)
{
    if(once) {
        printf("MR LLRF does not allow to run multiple instances.\n");
        return;
    }

    once = 1;

    mrLlrfAsynDriverConfigure(args[0].sval);
}

void mrLlrfAsynDriverRegister(void)
{
    iocshRegister(&initFuncDef, initCallFunc);
}

epicsExportRegistrar(mrLlrfAsynDriverRegister);


/* EPICS driver support for mrLlrfAsynDriver */

static int mrLlrfAsynDriverReport(int interest);
static int mrLlrfAsynDriverInitialize(void);
static struct drvet mrLlrfAsynDriver = {
    2,
    (DRVSUPFUN) mrLlrfAsynDriverReport,
    (DRVSUPFUN) mrLlrfAsynDriverInitialize
};


epicsExportAddress(drvet, mrLlrfAsynDriver);




static int mrLlrfAsynDriverReport(int interest)
{
    printCounters();
    printElapsedTimeMeasure();
    mrLlrfDataProc_report();

    return 0;
}


static int mrLlrfAsynDriverInitialize(void)
{

    mrLlrfProcTaskArg *p;
	
	if(!once) printf("Driver Initialization is so early. (%s)\n", driverName);
	else      printf("Driver Iniitalization is good. (%s)\n", driverName);
	
	p = (mrLlrfProcTaskArg *) malloc(sizeof(mrLlrfProcTaskArg));
	strcpy(p->name, "mrLlrfProcTask");
	
	epicsThreadCreate(p->name, epicsThreadPriorityHigh, 
	                  epicsThreadGetStackSize(epicsThreadStackMedium),
					  (EPICSTHREADFUNC) mrLlrfProcTask, (void *) p);
	
    return 0;
}



}  /* extern C */
