/* ======================================================================== *\
!
! *
! * 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): Daniela Dorner, 01/2005 <mailto:dorner@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2000-2006
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// checkfileavail.C
// ================
//
// check the availability of the files of one sequence:
// the script filesondisk has inserted the information (which files are on
// disk into the database) and with this macro this information is checked
// for the runs of one sequence
//
// executing the macro:
//  .x checkfileavail.C+("sequencefile")
// the sequencefile (including path) has to be given, as the macro retrieves
// from there the runnumbers
//
// the macro returns 0, if there's no connection to the database, 2, if a
// file is missing, and 1 if all files are there
// the return value is checked by the script, that executes the macro
//
// this macro is very similar to the macro checkstardone.C
//
/////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <iomanip>
#include <fstream>

#include <TEnv.h>

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

using namespace std;


//check the value of a column for a run
//if a file is not available, the column contains nothing (NULL) - this value is returned
TString GetStatus(MSQLServer &serv, TEnv &rc, TString primary, TString table, TString column)
{
    TString query(Form("SELECT %s FROM %s WHERE %s=%s",
                       column.Data(), table.Data(),
                       rc.GetValue(table+".Primary", ""),
                       primary.Data()));

    cout << "Query: " << query << endl;

    TSQLResult *res = serv.Query(query);
    if (!res)
    {
        cout << "Error - no run to check" << endl;
        return "";
    }

    TSQLRow *row=0;
    while ((row = res->Next()))
    {
//        TString entry=(*row)[0];
//        if (entry=="1970-01-01 00:00:00")
//            return "";
        return (*row)[0];
    }

    return "";
}

int checkfileavail(TString sequencefile)
{
    TEnv env("sql.rc");

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

    TEnv rc("steps.rc");

    //reading runnumbers from Sequencefile
    TEnv sequ(sequencefile);
    cout << "sequ file: " << sequencefile.Data() << endl;
    TString runs;
    runs = sequ.GetValue("Runs", "");
    runs.ReplaceAll(" ", ",");
    if (runs.IsNull())
    {
        cout << "ERROR - No runs in file " << sequencefile << " found." << endl;
        return 0;
    }

    //getting runnumbers from database
    //(not neccessary anymore -> can be changed)
    TString query(Form("SELECT fRunNumber FROM RunData WHERE fRunNumber in (%s)",
                       runs.Data()));

    TSQLResult *res = serv.Query(query);
    if (!res)
        cout << "Error - no run to check" << endl;

    //check for each run the availability of files from the table RunProcessStatus
    //the following columns have to be checked:
    //fCCFileAvail, fCaCoFileAvail, fCaCoFileFound, fRawFileAvail, fTimingCorrection
    //fTimingCorrection has to be checked, as only rawfiles with correct timing should be calibrated
    TSQLRow *row=0;
    while ((row = res->Next()))
    {
        TString runno=(*row)[0];
        cout << "run#: " << runno << endl;
        //if one value returns "" (i.e. column is NULL), 0 is returned
        if (GetStatus(serv, rc, runno, "RunProcessStatus", "fCCFileAvail")==""
            || GetStatus(serv, rc, runno, "RunProcessStatus", "fCaCoFileAvail")==""
            || GetStatus(serv, rc, runno, "RunProcessStatus", "fCaCoFileFound")==""
            || GetStatus(serv, rc, runno, "RunProcessStatus", "fTimingCorrection")==""
//            || GetStatus(serv, rc, runno, "RunProcessStatus", "fTimingCorrection")=="1970-01-01 00:00:00"
            || GetStatus(serv, rc, runno, "RunProcessStatus", "fRawFileAvail")=="")
            return 2;
    }
    //if all values are okay (i.e. files are availabel), 1 is returned
    return 1;

}

