#include "DataProcessorImp.h"

#include "FAD.h"
#include "tools.h"

#include "DimWriteStatistics.h" // weird dependency

using namespace std;


// --------------------------------------------------------------------------
//
//! This creates an appropriate file name for a particular run number and type
//! @param runNumberq the run number for which a filename is to be created
//! @param runType an int describing the kind of run. 0=Data, 1=Pedestal, 2=Calibration, 3=Calibrated data
//! @param extension a string containing the extension to be appened to the file name
//
string DataProcessorImp::FormFileName(const string &path, uint64_t night, uint32_t runid, const string &extension)
{
    ostringstream name;

    if (!path.empty())
    {
        name << path;
        if (path[path.length()-1] != '/')
            name << '/';
    }

    name << Tools::Form("%04d/%02d/%02d/", night/10000, (night/100)%100, night%100);

    try
    {
        DimWriteStatistics::CreateDirectory(name.str());
    }
    catch (const runtime_error &)
    {
        // File creation will fail anyway
        //Error(e.what());
    }

    name << night << '_' << setfill('0') << setw(3) << runid << '.' << extension;
    return name.str();
}

// =======================================================================

bool DataDump::Open(const RUN_HEAD* h, const FAD::RunDescription &)
{
    fFileName = "/dev/null";

    ostringstream str;
    str << this << " - "
        << "OPEN_FILE #" << GetRunId() << ":"
        << " Ver=" << h->Version
        << " Typ=" << h->RunType
        << " Nb="  << h->NBoard
        << " Np="  << h->NPix
        << " NTm=" << h->NTm
        << " roi=" << h->Nroi;

    Debug(str);

    fTime = Time();

    return true;
}

bool DataDump::WriteEvt(EVENT *e)
{
    const Time now;
    if (now-fTime<boost::posix_time::seconds(5))
        return true;

    fTime = now;

    ostringstream str;
    str << this << " - EVENT #" << e->EventNum << " / " << e->TriggerNum;
    Debug(str);

    return true;
}

bool DataDump::Close(RUN_TAIL *)
{
    ostringstream str;
    str << this << " - CLOSE FILE #" << GetRunId();

    Debug(str);

    return true;
}

// =======================================================================

bool DataDebug::WriteEvt(EVENT *e)
{
    cout << "WRITE_EVENT #" << GetRunId() << " (" << e->EventNum << ")" << endl;
    cout << " Typ=" << e->TriggerType << endl;
    cout << " roi=" << e->Roi << endl;
    cout << " trg=" << e->SoftTrig << endl;
    cout << " tim=" << e->PCTime << endl;

    return true;
}

