#include <stdio.h>

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

#include "gmdBSA.h"
#include "ATCACommon.h"

// Singleton design pattern: initialize class instance pointer to null.
GmdBSA* GmdBSA::instance = 0;

void bsaCallbackFunction(void* pBuf, unsigned size,  epicsTimeStamp time, int timeslot, void* usr) {
    // We assume that all data comes with a header
    class GmdBSA* gmdBSA;
    gmdBSA = GmdBSA::getInstance();
    gmdBSA->updateData(* (gmd_stream_with_header_t*) pBuf, time);
    gmdBSA->gmdBSAThread.resume();
}

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

    return instance;
}

GmdBSA::GmdBSA()
    : gmdBSAThread (*this, "gmdBSA", 
                    epicsThreadGetStackSize(epicsThreadStackMedium),
                    epicsThreadPriorityHigh + 3)
{
    initialized = false;

    // Although we are going to create the channels, each IOC decides which one
    // will be used. Some are optional.
    photonEnBsaChannel = NULL;
    posXBsaChannel = NULL;
    posYBsaChannel = NULL;
}

void GmdBSA::initialize(const char* portName, const char* photonEnChannelName, 
                        const char* posXChannelName, const char* posYChannelName)
{
    // Guarantee that initialize is called only once.
    if (! initialized) {
        initialized = true;

        streamPortName = portName;
        
        addChannels(photonEnChannelName, posXChannelName, posYChannelName);

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

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

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

    // Store updated data in BSA Core and suspends until next callback brings
    // new data
    while (! stopRunning) {
        bsaData.stat = epicsAlarmNone;
        bsaData.sevr = epicsSevNone;

        // For energy below a configured threshold, we consider it zero.
        if (GmdDebugStream::isStatusEnergyLow(bsaData.statusFromFirmware)) {
            bsaData.photonEn = 0.0;
        }

        // If the firmware flags that the energy is invalid or it is the result of
        // a soft trigger, this data is useless for the BSA.
        if (GmdDebugStream::isStatusEnergyInvalid(bsaData.statusFromFirmware) ||
            GmdDebugStream::isStatusSoftTrigger(bsaData.statusFromFirmware)) 
        {
            bsaData.stat = epicsAlarmCalc;
            bsaData.sevr = epicsSevInvalid; 
        }

        if (GmdDebugStream::isStatusCalibCycle(bsaData.statusFromFirmware)) {
            bsaData.stat = epicsAlarmState;
            bsaData.sevr = epicsSevMinor;
        }

        // Store data in BSA Core
        if (photonEnBsaChannel) {
            BSA_StoreData(photonEnBsaChannel, bsaData.time, bsaData.photonEn,
                      bsaData.stat, bsaData.sevr);
        }

        if (posXBsaChannel) {
            BSA_StoreData(posXBsaChannel, bsaData.time, bsaData.y_pos,
                      bsaData.stat, bsaData.sevr);
        }
        
        if (posYBsaChannel) {
            BSA_StoreData(posYBsaChannel, bsaData.time, bsaData.y_pos,
                      bsaData.stat, bsaData.sevr);
        }
        
        gmdBSAThread.suspendSelf();
    }
}

// The callback calls this method everytime new data arrives from the firmware
void GmdBSA::updateData(gmd_stream_with_header_t rawData, epicsTimeStamp time) {
    bsaData.time = time;
    bsaData.photonEn = rawData.packet.tmit_fp;
    bsaData.x_pos = rawData.packet.x_pos_fp;
    bsaData.y_pos = rawData.packet.y_pos_fp;
    bsaData.statusFromFirmware = rawData.packet.status;
}

// Create BSA channels or get the handles if they were already created. Note
// that each IOC can have a different set of channels. An empty string will
// tell whether the channel is not used by the IOC.
void GmdBSA::addChannels(const char* photonEnChannelName, const char* posXChannelName, const char* posYChannelName) {
    if (photonEnChannelName && strlen(photonEnChannelName)) {
        photonEnBsaChannel = BSA_CreateChannel(photonEnChannelName);
    }

    if (posXChannelName && strlen(posXChannelName)) {
        posXBsaChannel = BSA_CreateChannel(posXChannelName);
    }

    if (posYChannelName && strlen(posYChannelName)) {
        posYBsaChannel = BSA_CreateChannel(posYChannelName);
    }
}
