/* ======================================================================== *\
!
! *
! * 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-2006
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// writesequencefile.C
// ===================
//
// reads the sequence information from the database and writes it into a
// txt file
//
// Usage:
//  .x writesequencefile.C+(sequno,"sequpath")
//
// Make sure, that database and password are corretly set in a resource
// file called sql.rc and the resource file is found.
//
// Returns 2 in case of failure, 1 in case of success and 0 if the connection
// to the database is not working.
//
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>

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

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

#include "MAstro.h"
#include "MTime.h"
#include "MDirIter.h"

#include "MSQLServer.h"

using namespace std;

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

    Int_t cnt=0;

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

    delete res;

    if (cnt==0)
    {
        cout << "ERROR - No " << name << " 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 %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();
    if (!row)
    {
        cout << "ERROR - No name in " << col << " for key " << n << endl;
        return "";
    }

    return (*row)[0];
}

Bool_t GetSequence(MSQLServer &serv, TSQLRow &data, TString sequpath)
{
    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;

    //create sequence file
    TString fname(Form("%s/%04d/sequence%08d.txt", sequpath.Data(), atoi(data[0])/10000, atoi(data[0])));
    cout << "Creating " << fname << "..." << flush;

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

    //write information into file
    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 << "ZdMin:           " << data[10] << endl;
    fout << "ZdMax:           " << data[11] << 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 RunData WHERE fSequenceFirst=%s AND fExcludedFDAKEY=1"
                       " AND fRunTypeKEY %%s ORDER BY fRunNumber",
                       data[0]));


    TString queryA(Form(query.Data(), "BETWEEN 2 AND 4"));
    TString queryC(Form(query.Data(), "BETWEEN 4 AND 4"));
    TString queryD(Form(query.Data(), "BETWEEN 2 AND 2"));
    TString queryP(Form(query.Data(), "BETWEEN 3 AND 3"));

    //write runs into sequence file
    if (!GetRuns(serv, fout, queryA, "Runs"))
        return kFALSE;

    fout << endl;

    if (!GetRuns(serv, fout, queryC, "CalRuns"))
        return kFALSE;
    if (!GetRuns(serv, fout, queryP, "PedRuns"))
        return kFALSE;
    if (!GetRuns(serv, fout, queryD, "DatRuns"))
        return kFALSE;

    fout << endl;

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

    return kTRUE;
}

// This tool will work from Period017 (2004_05_17) on...
int writesequencefile(Int_t sequno, TString sequpath)
{
    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;

    //get sequence information from database
    TString query(Form("SELECT fSequenceFirst, fSequenceLast, fProjectKEY, fSourceKEY,"
                       " fL1TriggerTableKEY, fL2TriggerTableKEY, fHvSettingsKEY, "
                       " fLightConditionsKEY, fRunStart, fNumEvents, "
                       " fZenithDistanceMin, fZenithDistanceMax "
                       " FROM Sequences WHERE fSequenceFirst=%d", sequno));
    TSQLResult *res = serv.Query(query);

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

    delete res;

    cout << endl;

    return 1;
}
