#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 "cpswKlystronAsynDriver.h"
#include "streamDispatch.h"
#include "streamDataType.h"

#include "registerTimeStampSource.h"

#include <yaml-cpp/yaml.h>
#include "yamlLoader.h"


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


static int32_t _intvl(struct timeval *s, struct timeval *t)
{
    int32_t intvl;

    intvl =  (t->tv_sec - s->tv_sec) * 1.E+6; // sec to usec
    intvl += (t->tv_usec - s->tv_usec);       // usec


    return intvl;
}


static double _pll_phase(int i)
{
    double v;
    
    v = (double) i / 32768. * 180.;
    
    return v;
}

static double _pll_amplitude16bit(int i)
{
    double v;
    
    v = (double)i / (double) (0x7fff +1);
    
    return v;
}

cpswKlystronAsynDriver::cpswKlystronAsynDriver(const char *portName)
    : asynPortDriver(portName,
                     1, /* number of elements of this device */
                     NUM_KLYSTRON_DET_PARAMS *2, /* number of asyn params to be cleared for each device */
                     asynInt32Mask | asynFloat64Mask | asynOctetMask | asynDrvUserMask | asynInt32ArrayMask | asynFloat64ArrayMask, /* Interface mask */
                     asynInt32Mask | asynFloat64Mask | asynOctetMask | asynEnumMask | 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*/
{

     pdone_mask = (uint8_t *)NULL;
     pflush_mask = (uint8_t *) NULL;
     pdone_count = (uint32_t *) NULL;
     pflush_count = (uint32_t *) NULL;
     pmutex    = (epicsMutex *)NULL;
     
     pTimingCoreLock = (epicsMutex*) new epicsMutex;
     pRtmLock        = (epicsMutex*) new epicsMutex;
     pevent_interlock = new epicsEvent;
     
     
     struct timeval t;
     gettimeofday(&t, NULL);
     
     
     try {
        Path p = cpswGetRoot();
        Path p_mmio = p->findByName("mmio");
        fw = IKlystronFw::create(p_mmio);

        // handles for streams
        for(int i=0; i<8; i++) {
            std::stringstream num;
            std::string str("Stream");
            num << str << i;
         
            strms.push_back (IStream::create(p->findByName(num.str().c_str()) ) );
        }

        output_enable = false; fw->OutputEnable(output_enable);              // disable output while setup
        cw_enable = false;     fw->CWOutputEnable(cw_enable);            // pulse mode only
        defaultSetup();                       // set up firmware with default values
        fw->initBuf();
        output_enable = true;  fw->OutputEnable(output_enable);
        
        // Reserve a debug stream for Beam Volts raw waveform (DC IN)
        fw->setDebugStreamSelect((IKlystronFw::StreamId) BEAMVOLTS_CHANNEL, (IKlystronFw::StreamSel) BEAMVOLTS_STREAM);
        
        fw->getRtmFirmwareVersion(&rtmFirmwareVersion);
        fw->getRtmSystemId(rtmSystemId);
        fw->getRtmSubType(rtmSubType);
        fw->getRtmFirmwareDate(rtmFirmwareDate);
        fw->msgNoDelay(0);  // use delayed timing pattern for application
        
        
        cnt_loPllUnlock = cnt_clockPllUnlock = cnt_adPllUnlock = 0;
        cntMode = 0;
        for(int i =0; i< 8; i++) cnt_jesd[0][i] = cnt_jesd[1][1] = 0;
        
        
        streamDispatchInit(); // Initialize the stream dispatch function at very first stage
        initRtmWaveforms();
        paramSetup();
        
        callParamCallbacks();

        printf("%s: paramSetup %d parameters\n", driverName, NUM_KLYSTRON_DET_PARAMS);
        
    } catch (CPSWError e) {
        fprintf(stderr, "CPSW Error: %s\n", e.getInfo().c_str());
        throw e;
    }


}


cpswKlystronAsynDriver::~cpswKlystronAsynDriver() {}

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


typedef struct {
    char name[64];
    int  stream_n;
} streamTaskArg;


void cpswKlystronAsynDriver::KlystronStreamTask(void *p)
{

    static std::vector<uint8_t> buf;
    static int init = 1;
    static uint8_t done_mask  = 0;
    static uint8_t flush_mask = 0;
    static uint32_t done_count = 0;
    static uint32_t flush_count = 0;
    static epicsMutex mutex;


    static struct timeval prev_t[8], curr_t[8];
    static int32_t  interval_max[8], interval_min[8];
    static uint32_t interval_reset = 0;
    
    for(int s = 0; s < 8; s++) { interval_max[s] = -10000;  interval_min[s] = 10000; }
    
    timing_header_t *p_time_header;
    
    pdone_mask   = &done_mask;
    pflush_mask  = &flush_mask;
    pdone_count  = &done_count;
    pflush_count = &flush_count;
    pinterval_reset = &interval_reset;
    pmutex       = &mutex;    
    

    std::vector<Stream>::iterator it;
    streamTaskArg *pArg = (streamTaskArg*) p;
    int i;

    for(it = strms.begin(), i=0; it != strms.end(); ++it, i++) {
        if(pArg->stream_n == i) break;
    }

    gettimeofday(curr_t +i, NULL);

    mutex.lock();    
    if(init) { // run at once by one instace. 
        init =0;
        buf.reserve(STREAM_BUFF_SIZE); 
        fw->setDaqSize(STREAM_LENGTH);
        // fw->armDaq();
    }
    mutex.unlock(); 
    
    while(1) {
        prev_t[i] = curr_t[i];
        gettimeofday(curr_t +i, NULL);
        uint32_t ret      = (*it)->read(&buf[i*STREAM_LENGTH], STREAM_LENGTH, /* CTimeout(50000000)*/ 50000);
        struct timeval *t = (struct timeval*) &buf[8*STREAM_LENGTH + i*sizeof(struct timeval)];
        int32_t *p_phase_error = (int32_t*) &buf[8*STREAM_LENGTH + 9*sizeof(struct timeval)];
        gettimeofday(t, NULL);

        if(ret < STREAM_LENGTH) {  // stall stream, flush all data in the stream

           
            while (ret) ret = (*it)->read(&buf[i*STREAM_LENGTH], STREAM_LENGTH, /*CTimeout(10000000)*/ 10000);
            
          
        }


        mutex.lock();
        if(ret) done_mask |= (0x01) << i;
        else    flush_mask |= (0x01) << i;

        if(done_mask == 0xff) {   // all 8 streams got data, and ready for data processing
            struct timeval *t = (struct timeval*) &buf[8*STREAM_LENGTH + 8*sizeof(struct timeval)];
            gettimeofday(t, NULL);
            
            p_time_header = (timing_header_t *) buf.data();


            /*
             * somehow, the word order for timestamp in data stream has been swapped.
             * we are gong to swap the word order in software side until firmware fix it.
             */

            //time = p_time_header->time;
            time.nsec = p_time_header->time.secPastEpoch;
            time.secPastEpoch = p_time_header->time.nsec;

            pulseid = PULSEID(time);
            updateTimeStamp();
            pevent_interlock->signal();
            fw->getIntPhaseError(&phase_error_firmware);
            *p_phase_error = phase_error_firmware;
            streamDispatch((void*) buf.data(), STREAM_BUFF_SIZE);
            done_mask = 0x00;
            flush_mask = 0x00;
            setIntegerParam(p_stream_done_cnt, ++done_count);
            updateTimeStamp();
            fw->armDaq();
            
            for(int s = 0; s <8; s++) {
                int32_t intv;
                setIntegerParam(p_stream_cycle_intv[s], intv = _intvl(prev_t +s, curr_t +s));
                setIntegerParam(p_stream_cycle_max[s],  interval_max[s] = (intv > interval_max[s])? intv: interval_max[s]);
                setIntegerParam(p_stream_cycle_min[s],  interval_min[s] = (intv < interval_min[s])? intv: interval_min[s]);
            }
            
            
        } else
 
        if(flush_mask == 0xff) {  // all 8 streams are flushed and ready for next data
            flush_mask = 0x00;
            done_mask  = 0x00;
            
            setIntegerParam(p_stream_flush_cnt, ++flush_count);
            // for(int s = 0; s < 8; s++) { interval_max[s] = interval_min[s] = 0; }
 
            fw->armDaq();
            
            
            callParamCallbacks();
        }
        
        else {
            // nothing todo 
            /*
             printf("Exception!: stream %d, ret %d,  done_mask %x  done_count %d, flush_mask %x flsuh_count %d\n", 
                       i, ret, done_mask, done_count, flush_mask, flush_count );
            */
            
            if(interval_reset) {
                interval_reset = 0;
                for(int s = 0; s < 8; s++) { interval_max[s] = -10000; interval_min[s] = 10000; }
            }
        }
        mutex.unlock();

    }
    
}


void cpswKlystronAsynDriver::KlystronInterlockTask(void *p)
{
   uint32_t st;
   rtmStatus = rtmFaultOutStatus = rtmAdcLockedStatus= rtmRFOffStatus = 0xffffffff;
   
   
   
    while(1) {
        pevent_interlock->wait();
        fw->cmdRtmRearm();
        
        fw->getRtmStatus(&st);              // read status register
        if(rtmStatus != st) {
            rtmStatus = st;
            setIntegerParam(p_rtmStatus, rtmStatus);   // update parameter space for the status register
        }
        
        fw->getRtmFaultOutStatus(&st);
        if(rtmFaultOutStatus != st) {
            rtmFaultOutStatus = st;
            setIntegerParam(p_rtmFaultOutStatus, rtmFaultOutStatus);
        }
        
        fw->getRtmAdcLockedStatus(&st);
        if(rtmAdcLockedStatus != st) {
            rtmAdcLockedStatus = st;
            setIntegerParam(p_rtmAdcLockedStatus, rtmAdcLockedStatus);
        }
        
        fw->getRtmRFOffStatus(&st);
        if(rtmRFOffStatus != st) {
            rtmRFOffStatus = st;
            setIntegerParam(p_rtmRFOffStatus, rtmRFOffStatus);
        }
        
        
        getRtmWaveforms();
        if(rtmFaultOutStatus) {  // 0 - no fault, 1 - fault
            takeRtmFaultHistory();
        }
        
        
        getRtmThresholdReadout();
              
        callParamCallbacks();
    }
}

void cpswKlystronAsynDriver::KlystronMonitorTask(void *p)
{
    while(1) {
        getTemperature();
        takePllStatus();
           
        callParamCallbacks();
        epicsThreadSleep(.5);
    }
}

void cpswKlystronAsynDriver::resetPllUnlockCounters(void)
{
    uint32_t v;
    
    fw->getLoPllUnlockCounter(&v);     cnt_loPllUnlock    = (int) v;
    fw->getClockPllUnlockCounter(&v);  cnt_clockPllUnlock = (int) v;
    fw->getAdPllUnlockCounter(&v);     cnt_adPllUnlock    = (int) v;
}

void cpswKlystronAsynDriver::resetJesdResyncCounters(void)
{
    uint32_t v;
    
    for(int jesd_idx = 0; jesd_idx < 2; jesd_idx++)
        for(int cnt_idx = 0; cnt_idx < 8; cnt_idx++) {
            fw->getJesdStatusValidCnt(&v, jesd_idx, cnt_idx); cnt_jesd[jesd_idx][cnt_idx] = v;
        }
}

void cpswKlystronAsynDriver::getTemperature(void)
{
    double temp;

    for(int i = 0; i < 8; i++) {
        fw->getTemp(i, &temp);
        setDoubleParam(p_temperature[i], temp);
    }

    fw->acqTemp();

}

void cpswKlystronAsynDriver::takePllStatus(void)
{
    uint32_t v;
    
    fw->getLoPllPhase(&v);        setIntegerParam(p_loPllPhase, (int) v);
                                  setDoubleParam(p_loPllPhaseDegree, _pll_phase((int) v));
    fw->getLoPllAmplitude(&v);    setIntegerParam(p_loPllAmplitude, (int) v);
                                  setDoubleParam(p_loPllNormAmplitude, _pll_amplitude16bit((int) v));
    fw->getLoPllLocked(&v);       setIntegerParam(p_loPllLocked, (v&0x1)?1:0);
    
    fw->getClockPllPhase(&v);     setIntegerParam(p_clockPllPhase, (int) v);
                                  setDoubleParam(p_clockPllPhaseDegree, _pll_phase((int) v));
    fw->getClockPllAmplitude(&v); setIntegerParam(p_clockPllAmplitude, (int) v);
                                  setDoubleParam(p_clockPllNormAmplitude, _pll_amplitude16bit((int) v));
    fw->getClockPllLocked(&v);    setIntegerParam(p_clockPllLocked, (v&0x1)?1:0);
    
    fw->getAdPllPhase(&v);        setIntegerParam(p_adPllPhase, (int) v);
                                  setDoubleParam(p_adPllPhaseDegree, _pll_phase((int) v));
    fw->getAdPllAmplitude(&v);    setIntegerParam(p_adPllAmplitude, (int) v);
                                  setDoubleParam(p_adPllNormAmplitude, _pll_amplitude16bit((int) v));
    fw->getAdPllLocked(&v);       setIntegerParam(p_adPllLocked, (v&0x1)?1:0);
    
    fw->getLoPllLossSignal(&v);    setIntegerParam(p_loPllLossSignal,    (v&0x1)?1:0);
    fw->getClockPllLossSignal(&v); setIntegerParam(p_clockPllLossSignal, (v&0x1)?1:0);
    fw->getAdPllLossSignal(&v);    setIntegerParam(p_adPllLossSignal,    (v&0x1)?1:0);
    
    fw->getLoPllUnlockCounter(&v);    setIntegerParam(p_loPllUnlockCounter,    cntMode?(int) v:((int) v - cnt_loPllUnlock));
    fw->getClockPllUnlockCounter(&v); setIntegerParam(p_clockPllUnlockCounter, cntMode?(int) v:((int) v - cnt_clockPllUnlock));
    fw->getAdPllUnlockCounter(&v);    setIntegerParam(p_adPllUnlockCounter,    cntMode?(int) v:((int) v - cnt_adPllUnlock));
    
    
    for(int jesd_idx = 0; jesd_idx < 2; jesd_idx++) {
        for(int cnt_idx = 0; cnt_idx < 8; cnt_idx++) {  
            fw->getJesdStatusValidCnt(&v, jesd_idx, cnt_idx);
            setIntegerParam(p_jesdResyncCnt[jesd_idx][cnt_idx], cntMode?(int) v:((int) v - cnt_jesd[jesd_idx][cnt_idx]));
        }
    }
    
    
    
}


void cpswKlystronAsynDriver::forceRearm(void)
{
    if(!pdone_mask || !pmutex) return;
    
    pmutex->lock();
    streamFlush();
    *pdone_mask = 0;
    fw->armDaq();
    pmutex->unlock();
}

void cpswKlystronAsynDriver::cpswKlystronReport(void)
{

    printf("  cpswKlystronAsynDriver\n");
    printf("      Output Enable/Disable:  %d\n", output_enable); 
    printf("      CW mode Enable/Disable: %d\n", cw_enable);
    printf("      Reference Channel #:    %d\n", ref_chn);
    printf("      Feedback Channel #:     %d\n", fdk_chn);
    printf("      Applyied window:  start %f (ns),  end %f (ns)\n", applStart_ns, applEnd_ns);
    printf("      Correction Scale: TS4 %f, TS1 %f\n", corrScale[0], corrScale[1]);
    printf("      Correction Angle: TS4 %f, TS1 %f\n", corrAngle[0], corrAngle[1]);
    printf("      -----\n");
    printf("      Stream read done mask: %x\n", *pdone_mask);
    printf("      Stream read flush mask: %x\n", *pflush_mask);
    printf("      Stream read done counter: %d\n", *pdone_count);
    printf("      Stream read flush counter: %d\n", *pflush_count); 

}

void cpswKlystronAsynDriver::cpswRtmReport(void)
{
    printf("  cpswRtm\n");
    printf("      RTM firmware version: %x\n", rtmFirmwareVersion);
    printf("      RTM system id       : %s\n", rtmSystemId);
    printf("      RTM subtype         : %s\n", rtmSubType);
    printf("      RTM firmware date   : %s\n", rtmFirmwareDate);
    
    reportRtmWaveformBuffer();
}


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


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



extern "C" {


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

}

epicsRegisterFunction(cpswKlystronTimeStampSource);


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

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

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

static int cpswKlystronAsynDriverConfigure(const char *portName)
{

    pKlystronDrv = new cpswKlystronAsynDriver(portName);

    strcpy(port_name, portName);
    

    return 0;
}


/* EPICS ioc shell commands */

static const iocshArg initArg0 = { "portName", iocshArgString };
static const iocshArg * const initArgs[] = { &initArg0 };
static const iocshFuncDef initFuncDef= { "cpswKlystronAsynDriverConfigure", 1, initArgs };
static void initCallFunc(const iocshArgBuf *args)
{
    if(once) {
        printf("KLYSTRON driver does not allow to run multiple instances.\n");
        return;
    }
    once =1;
    cpswKlystronAsynDriverConfigure(args[0].sval);
}

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

epicsExportRegistrar(cpswKlystronAsynDriverRegister);


/* EPICS Driver Support for cpswKlystronAsynDriver */

static int cpswKlystronAsynDriverReport(int interest);
static int cpswKlystronAsynDriverInitialize(void);
static struct drvet cpswKlystronAsynDriver = {
    2,
    (DRVSUPFUN) cpswKlystronAsynDriverReport,
    (DRVSUPFUN) cpswKlystronAsynDriverInitialize
};

epicsExportAddress(drvet, cpswKlystronAsynDriver);



static int cpswKlystronAsynDriverReport(int interest)
{
    if(!once) return 0;
    
    if(!pKlystronDrv) return 0;
    
    pKlystronDrv->cpswKlystronReport();
    pKlystronDrv->cpswRtmReport();
    
    streamSubscrReport();
    
    
    return 0;
}

static int cpswKlystronAsynDriverInitialize(void)
{
    int i;
    streamTaskArg *p;

    if(!once) printf("Driver Initialization is so early. (%s)\n", driverName);
    else      printf("Driver Initialization is good. (%s)\n", driverName);
    
    for(i = 0; i<8; i++) { 
        p = (streamTaskArg *) malloc(sizeof(streamTaskArg));
        sprintf(p->name, "streamTask%d",i);
        p->stream_n =i;
 
        epicsThreadCreate(p->name, epicsThreadPriorityHigh + 3,
                  epicsThreadGetStackSize(epicsThreadStackMedium),
                  (EPICSTHREADFUNC) KlystronStreamTask, (void *) p);

    }
    
    epicsThreadCreate("interlockTask", epicsThreadPriorityHigh + 1,
                      epicsThreadGetStackSize(epicsThreadStackMedium),
                      (EPICSTHREADFUNC) KlystronInterlockTask, (void*) NULL);
                      
    epicsThreadCreate("monitorTask", epicsThreadPriorityHigh - 10,
                      epicsThreadGetStackSize(epicsThreadStackMedium),
                      (EPICSTHREADFUNC) KlystronMonitorTask, (void*) NULL);
    
    return 0;
}


} /* extern C */
