#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 "KlystronAsynDriver.h"
#include "streamDispatch.h"
#include "streamDataType.h"
#include "streamDataProc.h"
#include "KlystronDataProc.h"

#include "registerTimeStampSource.h"


static const char *driverName = "KlystronAsynDrver";
static char port_name[32];
static int once = 0;
static class KlystronAsynDriver *pKlystronDrv;

static char bsaStationName[80];


KlystronAsynDriver::KlystronAsynDriver(const char *portName)
    : asynPortDriver(portName,
                     1, /* number of elements of this device */
                     NUM_KLYSTRON_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", "Klystron", portName);
  	stream_subscribe_id = streamSubscribe(stream_name);
    bsaStationName[0] = '\0';
	  
	  if(initChnData()) printf("malloc error for Klystron stream proc\n");
    if(KlystronDataProc_init()) printf("malloc error for Klystron data proc\n");

    printf("%s: paramSetup %d parameters\n", driverName, NUM_KLYSTRON_DET_PARAMS);
    paramSetup(); 

}
 
KlystronAsynDriver::~KlystronAsynDriver() {}

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

void KlystronAsynDriver::KlystronProcess(void *buf, unsigned timeslot)
{
    KlystronDataProc_collectDaq(buf, timeslot);
    KlystronDataProc_delayMeasure(buf, DAQ);
    
    KlystronDataProc_calcSignal(buf, timeslot);
    KlystronDataProc_delayMeasure(buf, CALC);
}

void KlystronAsynDriver::KlystronPVProcess(void *buf, unsigned timeslot)
{
    for(int i = 0; i< MAX_CHANNEL_NUMBER; i++) {
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].avg_phase, KlystronDataProc_getAvgPhase(i, timeslot));            // update phase for each channel
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].avg_amplitude, KlystronDataProc_getAvgAmplitude(i, timeslot));    // update amplitude for each channel
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].avg_power,  KlystronDataProc_getAvgPower(i, timeslot));           // update power for each channel
        setDoubleParam(p_signalWaveform[i][ts(timeslot)].refsub_phase, KlystronDataProc_getRefSubPhase(i, timeslot));      // update reference subtracted phase for each channel

        setDoubleParam(p_signalWaveform_tsUnaware[i].avg_phase, nan(""));     setDoubleParam(p_signalWaveform_tsUnaware[i].avg_phase, KlystronDataProc_getAvgPhase(i, timeslot));
                                                                              BSA_StoreData(BsaChn_PACT[i], time, KlystronDataProc_getAvgPhase(i, timeslot), 0, 0); 
        setDoubleParam(p_signalWaveform_tsUnaware[i].avg_amplitude, nan("")); setDoubleParam(p_signalWaveform_tsUnaware[i].avg_amplitude, KlystronDataProc_getAvgAmplitude(i, timeslot));
                                                                              BSA_StoreData(BsaChn_AACT[i], time, KlystronDataProc_getAvgAmplitude(i, timeslot), 0, 0);
        setDoubleParam(p_signalWaveform_tsUnaware[i].avg_power, nan(""));     setDoubleParam(p_signalWaveform_tsUnaware[i].avg_power, KlystronDataProc_getAvgPower(i, timeslot));
        setDoubleParam(p_signalWaveform_tsUnaware[i].refsub_phase, nan(""));  setDoubleParam(p_signalWaveform_tsUnaware[i].refsub_phase, KlystronDataProc_getRefSubPhase(i, timeslot)); 
    }

    setDoubleParam(p_phase_firmware[ts(timeslot)], KlystronDataProc_getPhaseFirmware(timeslot));   
    setDoubleParam(p_phase[ts(timeslot)], KlystronDataProc_getPhase(timeslot));
    setDoubleParam(p_amplitude[ts(timeslot)], KlystronDataProc_getAmplitude(timeslot));
    setDoubleParam(p_power[ts(timeslot)], KlystronDataProc_getPower(timeslot));
    
    setDoubleParam(p_bvoltPeak[ts(timeslot)], KlystronDataProc_getBvoltPeak(timeslot));
    setDoubleParam(p_bvoltPeak_tsUnaware, nan(""));
    setDoubleParam(p_bvoltPeak_tsUnaware, KlystronDataProc_getBvoltPeak(timeslot));
    BSA_StoreData(BsaChn_BVOLT, time, KlystronDataProc_getBvoltPeak(timeslot), 0, 0);
    
    setDoubleParam(p_prev_p_corr[ts(timeslot)], KlystronDataProc_getPrevPCorr(timeslot));   // previous dac set vlaues need to be updated always
    setDoubleParam(p_prev_a_corr[ts(timeslot)], KlystronDataProc_getPrevACorr(timeslot));   // previous dac set values need to be udpated always
    
    setDoubleParam(p_p_err[ts(timeslot)], KlystronDataProc_getPErr(timeslot));
    
    setDoubleParam(p_p_corr[ts(timeslot)], KlystronDataProc_getPCorr(timeslot));
    setDoubleParam(p_a_corr[ts(timeslot)], KlystronDataProc_getACorr(timeslot));
    
    
    callParamCallbacks();
    
}

void KlystronAsynDriver::KlystronSigWfPosting(void *buf, unsigned timeslot)
{
     Klystron_rfData_t *pRf;
     
     double bvolt_scale;
     double beamVoltsWf[RAWRF_SMPL_SIZE];
   
     if(ts(timeslot) < 0) return; // invalid timeslot 
          
     for (int i = 0; i < MAX_CHANNEL_NUMBER; i++) {
         pRf = KlystronDataProc_getDataPointer(i, timeslot);
               
         // waveform post for beam volts
         if( i == BEAMVOLTS_CHANNEL ) {
             bvolt_scale = KlystronDataProc_getBvoltScale();
             for (int j = 0; j < pRf->num_raw; j++) { beamVoltsWf[j] = bvolt_scale * pRf->raw[j]; }
             doCallbacksFloat64Array(beamVoltsWf, pRf->num_raw, p_bvoltWf[ts(timeslot)], 0);
         }
         
         // waveform post for raw RF signal
         
         if( i < MAX_RAW_CHANNEL_NUMBER ) { 
             doCallbacksInt16Array(pRf->raw, pRf->num_raw, p_signalWaveform[i][ts(timeslot)].raw, 0);
         }
         
         // waveform post for phase
             doCallbacksFloat64Array(pRf->phase, pRf->num_phase, p_signalWaveform[i][ts(timeslot)].phase, 0);
         
         // waveform post for amplitude
             doCallbacksFloat64Array(pRf->amplitude, pRf->num_amplitude, p_signalWaveform[i][ts(timeslot)].amplitude, 0);
         
         
     }
       
     KlystronDataProc_delayMeasure(buf, PVPOST);
     
        
}

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

void KlystronAsynDriver::KlystronProcTask(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>6 || ts(timeslot) <0) continue;

        // allow data processing for all 6 timeslots
        // if(timeslot != 4 && timeslot != 1) continue;

        p_time_header = (timing_header_t*) buf;


        /*
         * somehow, the word order for timestamp has been changed in stream data  
         * we are going to swap the words in software side until firmware fix it up
         */
        // time = p_time_header->time;
        time.nsec = p_time_header->time.secPastEpoch;
        time.secPastEpoch = p_time_header->time.nsec;


        updateTimeStamp();
           
        KlystronProcess(buf, timeslot);    
        KlystronPVProcess(buf, timeslot);    // real-time
        KlystronSigWfPosting(buf, timeslot);
        
	    
	}

}

int KlystronAsynDriver::ts(unsigned timeslot)
{
  /*   timeslot   0, 1, 2, 3, 4, 5, 6 */  // input
  /* array index -1, 1, 2, 3, 0, 4, 5 */  // output
  
    int _ts[] = {-1, 1, 2, 3, 0, 4, 5 };
    
    if(timeslot > 6) return -1;
    
    return _ts[timeslot];
}


void KlystronAsynDriver::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++) {
        for(ts = 1; ts <=6; ts++) {
            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);
        }
        
    }
}


static void resetElapsedTimeMeasure(void)
{
    unsigned c, ts;

    for(c = 0; c < MAX_CHANNEL_NUMBER; c++) {
        for(ts = 1; ts <=6; ts++) reset_elapsedTimeMeasure(c, ts);

    }
}

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);
                
        for(ts = 1; ts <=6; ts ++) {
            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 KlystronTimeStampSource(void *puserPvt, epicsTimeStamp *pTime)
{
    adTimeStampSource_p  pTss = (adTimeStampSource_p) puserPvt;
    if(!pTss) return;
    
    if(pKlystronDrv) pKlystronDrv->TimeStampSourceProcess(pTss, pTime);

}

epicsRegisterFunction(KlystronTimeStampSource);


static void KlystronProcTask(void *p)
{
    if(pKlystronDrv) pKlystronDrv->KlystronProcTask(p);

}


static int KlystronAsynDriverConfigure(const char *portName) 
{
    
    pKlystronDrv = new KlystronAsynDriver(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 = {"KlystronConfigure", 1, initArgs };
static void initCallFunc(const iocshArgBuf * args)
{
    if(once) {
        printf("MR KLYSTRON does not allow to run multiple instances.\n");
        return;
    }

    once = 1;

    KlystronAsynDriverConfigure(args[0].sval);
}


static const iocshFuncDef resetTimeFuncDef = { "KlystronResetDelay", 0, NULL };
static void resetTimeCallFunc(const iocshArgBuf * args)
{

    KlystronDataProc_resetDelayMeasurements();
    resetElapsedTimeMeasure();
}

static const iocshArg bsaStationArg0 = { "station name for BSA", iocshArgString };
static const iocshArg * const bsaStationArgs [] = { &bsaStationArg0 };
static const iocshFuncDef bsaStationFuncDef = {"Klystron_bsaStationName", 1, bsaStationArgs };
static void bsaStationCallFunc(const iocshArgBuf * args)
{
    strcpy(bsaStationName, args[0].sval);
    if(pKlystronDrv && bsaStationName[0]) pKlystronDrv->bsaSetup(bsaStationName);
}



void KlystronAsynDriverRegister(void)
{
    iocshRegister(&initFuncDef, initCallFunc);
    iocshRegister(&resetTimeFuncDef, resetTimeCallFunc);
    iocshRegister(&bsaStationFuncDef, bsaStationCallFunc);
}

epicsExportRegistrar(KlystronAsynDriverRegister);




/* EPICS driver support for KlystronAsynDriver */

static int KlystronAsynDriverReport(int interest);
static int KlystronAsynDriverInitialize(void);
static struct drvet KlystronAsynDriver = {
    2,
    (DRVSUPFUN) KlystronAsynDriverReport,
    (DRVSUPFUN) KlystronAsynDriverInitialize
};


epicsExportAddress(drvet, KlystronAsynDriver);




static int KlystronAsynDriverReport(int interest)
{
    printCounters();
    printElapsedTimeMeasure();
    KlystronDataProc_report();

    return 0;
}


static int KlystronAsynDriverInitialize(void)
{

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



}  /* extern C */
