/* ======================================================================== *\
!
! *
! * This file is part of MARS, the MAGIC Analysis and Reconstruction
! * Software. It is distributed to you in the hope that it can be a useful
! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
! * It is distributed WITHOUT ANY WARRANTY.
! *
! * Permission to use, copy, modify and distribute this software and its
! * documentation for any purpose is hereby granted without fee,
! * provided that the above copyright notice appear in all copies and
! * that both that copyright notice and this permission notice appear
! * in supporting documentation. It is provided "as is" without express
! * or implied warranty.
! *
!
!
!   Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
!   Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// writesequencefile.C
// ===================
//
// reads the sequence information from the database
// and writes it into a txt file
//
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>

#include <MSQLServer.h>
#include <TSQLRow.h>
#include <TSQLResult.h>

#include <TEnv.h>
#include <TMath.h>
#include <TRegexp.h>

#include <MAstro.h>
#include <MTime.h>
#include <MDirIter.h>

using namespace std;

Bool_t GetAllRuns(MSQLServer &serv, ofstream &fout, TString query)
{
    TSQLResult *res = serv.Query(query);
    if (!res)
        return kFALSE;

    TSQLRow *row=0;

    Int_t cnt = 0;

    fout << "Runs:";
    while ((row = res->Next()))
    {
        fout << " " << (*row)[0];
        cnt++;
    }
    fout << endl;

    delete res;

    if (cnt==0)
    {
        cout << "ERROR - No runs belonging to this sequence found." << endl;
        return kFALSE;
    }

    return kTRUE;
}

Bool_t GetCalRuns(MSQLServer &serv, ofstream &fout, TString query, MTime *t)
{
    TSQLResult *res = serv.Query(query);
    if (!res)
        return kFALSE;

    Int_t first = 0;
    Int_t cnt   = 0;

    fout << "CalRuns:";
    TSQLRow *row=0;
    while ((row = res->Next()))
        if ((*row)[1][0]=='4')
        {
            fout << " " << (*row)[0];
            cnt++;

            if (!first)
            {
                t[0].SetSqlDateTime((*row)[2]);
                first = 1;
            }
            t[1].SetSqlDateTime((*row)[3]);
        }
    fout << endl;

    delete res;

    if (cnt==0)
    {
        cout << "ERROR - No calibration runs belonging to this sequence found." << endl;
        return kFALSE;
    }

    return kTRUE;
}

Bool_t GetPedRuns(MSQLServer &serv, ofstream &fout, TString query, MTime *t)
{
    Int_t cnt = 0;

    fout << "PedRuns:";

    Int_t tot = 0;

    while (tot<1000)
    {
        TSQLResult *res = serv.Query(query);
        if (!res)
            return kFALSE;

        Int_t idx = 0;
        Int_t n = 0;
        Double_t diff = 1e35;
        MTime start, stop;

        TSQLRow *row=0;
        while ((row=res->Next()))
        {
            if ((*row)[1][0]=='3' || (cnt>1 && idx==0 && (*row)[1][0]=='2'))
            {
                MTime t0, t1;
                t0.SetSqlDateTime((*row)[2]);
                t1.SetSqlDateTime((*row)[3]);

                if ((Double_t)t[0]-(Double_t)t1<diff && t[0]>t1)
                {
                    diff = (Double_t)t[0]-(Double_t)t1;
                    idx = atoi((*row)[0]);
                    n = atoi((*row)[4]);
                    start = t0;
                    stop = t1;
                }
                if ((Double_t)t0-(Double_t)t[1]<diff && t0>t[1])
                {
                    diff = (Double_t)t0-(Double_t)t[1];
                    idx = atoi((*row)[0]);
                    n = atoi((*row)[4]);
                    start = t0;
                    stop = t1;
                }
            }
        }

        tot += n;
        if (idx!=0)
            fout << " " << idx;
        cnt ++;

        delete res;

        if (start<t[0])
            t[0] = start;
        if (stop>t[1])
            t[1] = stop;
    }

    fout << endl;

    if (cnt==0)
    {
        cout << "ERROR - No pedestal (data) runs belonging to this sequence found." << endl;
        return kFALSE;
    }

    return kTRUE;
}

Bool_t GetDatRuns(MSQLServer &serv, ofstream &fout, TString query)
{
    TSQLResult *res = serv.Query(query);
    if (!res)
        return kFALSE;

    Int_t cnt=0;

    fout << "DatRuns:";
    TSQLRow *row=0;
    while ((row = res->Next()))
        if ((*row)[1][0]=='2')
        {
            fout << " " << (*row)[0];
            cnt++;
        }
    fout << endl;

    delete res;

    if (cnt==0)
    {
        cout << "ERROR - No data runs belonging to this sequence found." << endl;
        return kFALSE;
    }

    return kTRUE;
}

TString GetName(MSQLServer &serv, const char *col, const char *n)
{
    TString query(Form("SELECT f%sName FROM MyMagic.%s WHERE f%sKEY=%s",
                       col, col, col, n));
    
    TSQLResult *res = serv.Query(query);
    if (!res)
    {
        cout << "ERROR - Resolving " << col << " failed! " << endl;
        return "";
    }

    TSQLRow *row = res->Next();
    return (*row)[0];
}

Bool_t GetSequence(MSQLServer &serv, TSQLRow &data)
{
    UShort_t y;
    Byte_t m, d;

    MTime time;
    time.SetSqlDateTime(data[8]);
    time.GetDateOfSunrise(y, m, d);

    TString date = Form("%04d-%02d-%02d", y, (int)m, (int)d);

    Int_t period = MAstro::GetMagicPeriod(time.GetMjd());

    TString str[6];
    str[0] = GetName(serv, "Project",         data[2]);
    str[1] = GetName(serv, "Source",          data[3]);
    str[2] = GetName(serv, "L1TriggerTable",  data[4]);
    str[3] = GetName(serv, "L2TriggerTable",  data[5]);
    str[4] = GetName(serv, "HvSettings",      data[6]);
    str[5] = GetName(serv, "LightConditions", data[7]);

    if (str[0].IsNull() || str[1].IsNull() || str[2].IsNull() || str[3].IsNull() || str[4].IsNull() || str[5].IsNull())
        return kFALSE;

    TString fname(Form("/mnt/stk01/sequences/%04d/sequence%08d.txt", atoi(data[0])/10000, atoi(data[0])));
    cout << "Creating " << fname << "..." << flush;

    ofstream fout(fname);
    if (!fout)
    {
        cout << "ERROR - Cannot open file." << endl;
        return kFALSE;
    }

    fout << "Sequence:        " << data[0] << endl;
    fout << "Period:          " << period  << endl;
    fout << "Night:           " << date    << endl;
    fout << "LightConditions: " << str[5] << endl;
    fout << endl;
    fout << "Start:           " << data[8] << endl;
    fout << "LastRun:         " << data[1] << endl;
    fout << "Project:         " << str[0]  << endl;
    fout << "Source:          " << str[1]  << endl;
    fout << "L1TriggerTable:  " << str[2]  << endl;
    fout << "L2TriggerTable:  " << str[3]  << endl;
    fout << "HvSettings:      " << str[4]  << endl;
    fout << "NumEvents:       " << data[9] << endl;
    fout << endl;

    TString query(Form("SELECT fRunNumber, fRunTypeKEY, fRunStart, fRunStop, fNumEvents"
                       " FROM MyMagic.RunData WHERE fSequenceFirst=%s AND fExcludedFDAKEY=1"
                       " ORDER BY fRunNumber",
                       data[0]));

    if (!GetAllRuns(serv, fout, query))
        return kFALSE;

    fout << endl;

    MTime t[2];
    if (!GetCalRuns(serv, fout, query, t))
        return kFALSE;
    if (!GetPedRuns(serv, fout, query, t))
        return kFALSE;
    if (!GetDatRuns(serv, fout, query))
        return kFALSE;

    fout << endl;

    cout << " done <Nevts=" << data[8] << ">" << endl;

    return kTRUE;
}

// This tool will work from Period017 (2004_05_17) on...
int writesequencefile(Int_t sequno)
{
    TEnv env("sql.rc");

    MSQLServer serv(env);
    if (!serv.IsConnected())
    {
        cout << "ERROR - Connection to database failed." << endl;
        return 0;
    }

    cout << "writesequencefile" << endl;
    cout << "-----------------" << endl;
    cout << endl;
    cout << "Connected to " << serv.GetName() << endl;
    cout << endl;

    TString query(Form("SELECT fSequenceFirst, fSequenceLast, fProjectKEY, fSourceKEY,"
                       " fL1TriggerTableKEY, fL2TriggerTableKEY, fHvSettingsKEY, "
                       " fLightConditionsKEY, fRunStart, fNumEvents"
                       " FROM MyMagic.Sequences WHERE fSequenceFirst=%d", sequno));
    TSQLResult *res = serv.Query(query);

    TSQLRow *row = 0;
    while ((row = res->Next()))
        if (!GetSequence(serv, *row))
            return 0;

    delete res;

    cout << endl;

    return 1;
}
