#include <math.h>

#include "gmdDebugStream.h"
#include "gmdBLD.h"

GmdDebugStream::GmdDebugStream(const char *portName, const char *named_root, const unsigned size, const bool header, const char *stream0, const char *stream1, const char *stream2, const char *stream3)
    : DebugStreamAsynDriver(portName,
                            named_root,
                            size,
                            header,
                            stream0,
                            stream1,
                            stream2,
                            stream3)
{
    createParam(p_EnergyString,       asynParamFloat64, &p_Energy);
    createParam(p_PosXString,         asynParamFloat64, &p_PosX);
    createParam(p_PosYString,         asynParamFloat64, &p_PosY);
    createParam(p_RmsAString,         asynParamFloat64, &p_RmsA);
    createParam(p_RmsBString,         asynParamFloat64, &p_RmsB);
    createParam(p_RmsCString,         asynParamFloat64, &p_RmsC);
    createParam(p_RmsDString,         asynParamFloat64, &p_RmsD);    
    createParam(p_EnableNCBldString,  asynParamInt32,   &p_EnableNCBld);
    
    for (int i = 0 ; i < 4; i++)
        s_type[i] = int16;
    /* Fix type here*/
}

GmdDebugStream::~GmdDebugStream () {

}


asynStatus GmdDebugStream::writeInt32(asynUser *pasynUser, epicsInt32 value)
{
    int function = pasynUser->reason;
    asynStatus status = asynSuccess;
    const char *functionName = "writeInt32";

    if(function == p_EnableNCBld) {
        /* set the parameter in the parameter library */
        status = (asynStatus) setIntegerParam(function, value);
        class GmdBLD* gmdBLD;
        gmdBLD = GmdBLD::getInstance();
        if (value == 1)
            gmdBLD->enable();
        else
            gmdBLD->disable();
        callParamCallbacks();
    } else{
        status = DebugStreamAsynDriver::writeInt32(pasynUser, value);
    }
    return status;
}


void GmdDebugStream::streamPoll(const int ch) {
    // First check if the user created the channel
    if(! _stream[ch]) {
        return;
    }

    try {
        rdLen[ch] = _stream[ch]->read(buff[ch], size, CTimeout(2000000));
    }
    catch (IOError &e) {
        // A timeout happened
        timeoutCnt ++;
        timeoutCnt_perStream[ch] ++;
    }
    catch (CPSWError &e) {
        // Don't print, as we are inside a polling. Wait for the next try, as
        // rdLen[ch] will be zero.
    }
    
    if(rdLen[ch] == 0 ) {
        return;
    }

    epicsTimeStamp time;
        
    rdCnt++; rdCnt_perStream[ch]++;

    if (dumpStreamInfo[ch].remainingPackets) {
        // Counter for loop
        std::size_t aaa; // To get rid of compiler warning messages
        // How many bytes to print during dump
        std::size_t byteQty = (std::size_t) dumpStreamInfo[ch].wordQty * 8 > rdLen[ch] ? rdLen[ch] : dumpStreamInfo[ch].wordQty * 8;

        printf("\nGMD BSA stream dump - %d packets remaining\n", dumpStreamInfo[ch].remainingPackets-1);
        printf("Message size: %d bytes\n", rdLen[ch]);
        for (aaa=0; aaa<byteQty; ++aaa) {
            // Print word number on first column
            if (!(aaa % 8)) {
                printf("\n%lu   ", aaa/8);
            }

            printf ("%02X ", buff[ch][aaa]);
        }

        printf("\n");
    }

    gmd_stream_with_header_t *p = (gmd_stream_with_header_t *) buff[ch];
    time.nsec               = p->packet.nsec;
    time.secPastEpoch       = p->packet.secPastEpoch;
        
    // The firmare brings us energies with maximum 2 mJ. To get higher
    // interpreted values we need to apply a multiplication factor.

    /* Dawood - removing tmit_fp, x_pos_fp and y_pos_fp assignments.
        *          Should be configured using three PVs, and done directly in
        *          hardware and the results should be the same
        *          EM1K0:GMD:HPS:XSclFP = 1 / 2^17
        *          EM1K0:GMD:HPS:YSclFP = 1 / 2^17
        *          EM1K0:GMD:HPS:EnSclFP = 1 / 2 ^ 13
        * https://confluence.slac.stanford.edu/pages/viewpage.action?spaceKey=ppareg&title=LCLS-II+HPS+BPM */

    //p->packet.tmit_fp       = p->packet.tmit; //EM1K0:GMD:HPS:milliJoulesPerPulse
    // TMIT/2^17 x 16 (2^4) ->  TmitSclFloatingPoint = 1 / 2 ^ 13
    //p->packet.x_pos_fp      = p->packet.x_pos_fp; EM1K0:GMD:HPS:POSX
    // x_pos_fp / 2^17 -> XSclFloatingPoint = 1 / 2^17
    //p->packet.y_pos_fp      = p->packet.y_pos_fp; EM1K0:GMD:HPS:POSY
    // y_pos_fp / 2^17 -> YSclFloatingPoint = 1 / 2^17

    // The GMD firmware does not send the timeslot information, so it goes as -1.
    // Call the functions that will use the header data.
    triggerCallbacks(ch, p, rdLen[ch], time, -1);

    // Print data decoded from stream dump
    if (dumpStreamInfo[ch].remainingPackets > 0) {
        printf("\nGMD BSA mapped data:\n");
        printf("tmit = %d\n", p->packet.tmit);
        printf("status = 0x%X\n", p->packet.status);
        printf("\tEnergy %s.\n", p->packet.status & ENERGY_INVALID_MASK ? "is invalid" : "is valid");
        printf("\tCalibration cycle is %s.\n", p->packet.status & CALIBRATION_CYCLE_MASK ? "running" : "not running");
        printf("\tThis measurement used a %s.\n", p->packet.status & SOFT_TRIGGER_MASK ? "soft trigger" : "hard trigger");
        printf("\tThe energy is %s the configured threashold.\n", p->packet.status & ENERGY_BELOW_THRESHOLD_MASK ? "below" : "above");
        if (isStatusOverFlow(p->packet.status)) printf("\tOverflow detected.\n");
        if (isStatusUnderFlow(p->packet.status)) printf("\tUnderflow detected.\n");
        printf("Reserved1 = %u\n", p->packet.reserved1);
        printf("header_length_version = %u\n", p->packet.header_length_version);
        printf("rmsA = %d\n", p->packet.rmsA);
        printf("rmsB = %d\n", p->packet.rmsB);
        printf("rmsC = %d\n", p->packet.rmsC);
        printf("rmsD = %d\n", p->packet.rmsD);
        printf("y_pos = %d\n", p->packet.y_pos);
        printf("x_pos = %d\n", p->packet.x_pos);
        printf("time.sec = %u\n", p->packet.secPastEpoch);
        printf("time.nsec = %u\n", p->packet.nsec);
        printf("Pulse Id = %llu\n", p->packet.pulseID);
        printf("TMIT-fp = %f\n", p->packet.tmit_fp);
        printf("Reserved2 = %u\n", p->packet.reserved2);
        printf("Y-fp = %f\n", p->packet.y_pos_fp);
        printf("X-fp = %f\n", p->packet.x_pos_fp);
        printf("Diff U = %d\n", p->packet.difU);
        printf("Sum U = %d\n", p->packet.sumU);
        printf("Diff V = %d\n", p->packet.difV);
        printf("Sum V = %d\n", p->packet.sumV);
        printf("quotV_r = %d\n", p->packet.quotV_r);
        printf("quotU_r = %d\n", p->packet.quotU_r);
        printf("Background CH0 = %d\n", p->packet.bkGrndCH0);
        printf("Background CH1 = %d\n", p->packet.bkGrndCH1);
        printf("Background CH2 = %d\n", p->packet.bkGrndCH2);
        printf("Background CH3 = %d\n", p->packet.bkGrndCH3);
        printf("\n");
    }

    setDoubleParam(p_Energy, p->packet.tmit_fp);
    setDoubleParam(p_PosX, p->packet.x_pos_fp);
    setDoubleParam(p_PosY, p->packet.y_pos_fp);
    setDoubleParam(p_RmsA, (double) p->packet.rmsA);
    setDoubleParam(p_RmsB, (double) p->packet.rmsB);
    setDoubleParam(p_RmsC, (double) p->packet.rmsC);
    setDoubleParam(p_RmsD, (double) p->packet.rmsD);    
    setTimeStamp(&time);
    callParamCallbacks();
    // GMD data has 4 waveforms with 16-bit interlaced values (64
    // bits in total) in little-endian representation. We need to
    // fix for big-endian systems. The 64-bit representation is
    // already fixed by the APIs. All we need to do is to read
    // each of the 16-bits of it in the easier order.


    int totalElements = (rdLen[ch] - sizeof(timing_header_t) - sizeof(packet_header_t))/sizeof(epicsInt16);
    for (int elementIndex = 0; elementIndex < totalElements; elementIndex++)
        doubleBuff[ch][elementIndex] = (double)((&p->payload.int16)[elementIndex]);   
    doCallbacksFloat64Array(doubleBuff[ch], totalElements, p_streamFloat64[ch], 0);    

    // Decrement dump packets counter in the end
    if (dumpStreamInfo[ch].remainingPackets > 0) {
        --dumpStreamInfo[ch].remainingPackets;
    }
}

bool GmdDebugStream::isStatusEnergyInvalid(epicsUInt16 statusBits) {
    return statusBits & ENERGY_INVALID_MASK;
}

bool GmdDebugStream::isStatusCalibCycle(epicsUInt16 statusBits) {
    return statusBits & CALIBRATION_CYCLE_MASK; 
}

bool GmdDebugStream::isStatusSoftTrigger(epicsUInt16 statusBits) {
    return statusBits & SOFT_TRIGGER_MASK; 
}

bool GmdDebugStream::isStatusEnergyLow(epicsUInt16 statusBits) {
    return statusBits & ENERGY_BELOW_THRESHOLD_MASK;
}

bool GmdDebugStream::isStatusUnderFlow(epicsUInt16 statusBits) {
    return statusBits & ENERGY_UNDERFLOW_MASK;
}

bool GmdDebugStream::isStatusOverFlow(epicsUInt16 statusBits) {
    return statusBits & ENERGY_OVERFLOW_MASK;
}