#include <stdio.h>

#include <alarm.h>
#include <epicsPrint.h>

#include "gmdBLD.h"
#include "gmd_data.h"
#include "bldPvClient.h"
#include "ATCACommon.h"

// Access to the global variable defined in gmdSub.cpp
extern GasMonitorDetectorData gmdData;

// Singleton design pattern: initialize class instance pointer to null.
GmdBLD* GmdBLD::instance = 0;
/**
 * @brief Callback function format
 * 
 * @param pBuf : buffer pointer
 * @param size  : size of buffer
 * @param time : Time of event
 * @param timeslot :  timeslot information from the timing pattern modifier 
 * @param usr : user private object pointer
 */
void bldCallbackFunction(void* pBuf, unsigned size,  epicsTimeStamp time, int timeslot, void* usr) {
    // We assume that all data comes with a header
    class GmdBLD* gmdBLD;
    gmdBLD = GmdBLD::getInstance();
    if (gmdBLD->isEnabled())
    {
        gmdBLD->updateData(* (gmd_stream_with_header_t*) pBuf, time);
        gmdBLD->gmdBLDThread.resume();
    }
}

// Singleton design pattern: get the instance pointer for the class. If it is
// the first time, create a new one.
GmdBLD* GmdBLD::getInstance() {
    if (instance == 0) {
        instance = new GmdBLD();
    }

    return instance;
}

void GmdBLD::disable()
{
    enableGmdBLD = false;
}

void GmdBLD::enable()
{
    enableGmdBLD = true;
}

bool GmdBLD::isEnabled()
{
    return enableGmdBLD;
}

GmdBLD::GmdBLD()
    : gmdBLDThread (*this, "gmdBLD", 
                    epicsThreadGetStackSize(epicsThreadStackMedium),
                    epicsThreadPriorityHigh + 3)
{
    initialized = false;
    enableGmdBLD = true;
}

void GmdBLD::initialize(const char* portName, int clientId)
{
    // Guarantee that initialize is called only once.
    if (! initialized) {
        initialized = true;

        streamPortName = portName;
        this->bldClientId = clientId;        

        stopRunning = false;
        gmdBLDThread.start();
    }
}   

GmdBLD::~GmdBLD() {
    stopRunning = true;
    epicsPrintf("GmdBLD: Stop pollThread\n");
    gmdBLDThread.resume();   
}

void GmdBLD::run() {
    // Waits until the Asyn driver with streamPortName is created or until the IOC is finished
    while ( registerStreamCallback(streamPortName.c_str(), 0, bldCallbackFunction,
            NULL) && ! stopRunning ) 
    {
        gmdBLDThread.sleep(1);
    }

    // Send updated data to the multicast network and suspends until next
    // callback brings new data
    while (! stopRunning) {
        // If the firmware flags that the energy is invalid or it is the result of
        // a soft trigger, this data is useless for the BLD.
        if (GmdDebugStream::isStatusEnergyInvalid(bldData.statusFromFirmware) ||
            GmdDebugStream::isStatusSoftTrigger(bldData.statusFromFirmware))
        { 
            bldData.milliJoulesPerPulse = NAN;
            bldData.x_pos = NAN;
            bldData.y_pos = NAN;
        }

        // For energy below a configured threshold, we consider it zero.
        if (GmdDebugStream::isStatusEnergyLow(bldData.statusFromFirmware)) {
            bldData.milliJoulesPerPulse = 0.0;
        }
        
        // Calculate size of buffer
        size_t sBufferMax =  (  sizeof(epicsFloat64) +   // Pulse-by-pulse pothon energy
                                sizeof(epicsFloat64) +   // Position X
                                sizeof(epicsFloat64) +   // Position Y
                                sizeof(epicsFloat64) +   // Avg photon energy from Keithley
                                sizeof(epicsInt64)   +   // Raw value of the sum of pulses RMS
                                sizeof(epicsInt16)   +   // Background noise of electron 1 signal
                                sizeof(epicsInt16)  );   // Background noise of electron 2 signal

        // Copy received data to buffer
        void* bufferRoot = malloc(sBufferMax);
        epicsFloat64* bufferRunnerFloat64 = static_cast<epicsFloat64*> (bufferRoot);
        *bufferRunnerFloat64++ = bldData.milliJoulesPerPulse; 
        *bufferRunnerFloat64++ = bldData.x_pos; 
        *bufferRunnerFloat64++ = bldData.y_pos;
        *bufferRunnerFloat64++ = bldData.avgPulseIntensity;

        epicsInt64* bufferRunnerInt64 = reinterpret_cast<epicsInt64*> (bufferRunnerFloat64);
        *bufferRunnerInt64++ = bldData.RawPulseRMS;

        epicsInt16* bufferRunnerInt16 = reinterpret_cast<epicsInt16*> (bufferRunnerInt64);
        *bufferRunnerInt16++ = bldData.electron1Bkgrnd;
        *bufferRunnerInt16++ = bldData.electron2Bkgrnd;

        BldSendPacket( bldClientId, GMD_BLD_ID, GMD_BLD_TYPE, &bldData.time, bufferRoot, sBufferMax );

        free(bufferRoot);

        // Wait until the callback arrives from the firmware stream data processing 
        gmdBLDThread.suspendSelf();
    }
}

// The callback calls this method everytime new data arrives from the firmware
void GmdBLD::updateData(gmd_stream_with_header_t rawData, epicsTimeStamp time) {
    bldData.time = time;
    bldData.statusFromFirmware = rawData.packet.status;
    bldData.milliJoulesPerPulse = rawData.packet.tmit_fp;
    bldData.x_pos = rawData.packet.x_pos_fp;
    bldData.y_pos = rawData.packet.y_pos_fp;
    bldData.avgPulseIntensity = gmdData.m_photons_mJ;
    bldData.RawPulseRMS = rawData.packet.tmit;
    bldData.electron1Bkgrnd = rawData.packet.bkGrndCH0;
    bldData.electron2Bkgrnd = rawData.packet.bkGrndCH1;
}
