#include "DataProcessorImp.h"

#include "FAD.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, uint32_t runid, const string &extension)
{
    ostringstream name;

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

    const Time time;

    const Time night = time - boost::posix_time::hours(12);

    name << night.GetAsStr("%Y/%m/%d/");

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

    name << time.NightAsInt() << '_' << 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;
}

