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

/////////////////////////////////////////////////////////////////////////////
//
// ResetAllRuns.C
// ==============
//
/////////////////////////////////////////////////////////////////////////////

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

#include <TEnv.h>

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

using namespace std;


int resetallruns(TString filename, TString column)
{
    TEnv env("sql.rc");

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

    TString query(Form("UPDATE RunProcessStatus SET %s=NULL",
                       column.Data()));
    if (column.Contains("CaCo"))
        query+=", fCaCoFileFound=NULL";


    cout << "q: " << query << endl;

    TSQLResult *res = serv.Query(query);
    if (!res)
    {
        cout << "updating (setting " << column.Data() << "= NULL) didn't work " << endl;
        return 0;
    }
    delete res;


    ifstream fin(filename);
    if (!fin)
    {
        cout << "file: " << filename << " missing!" << endl;
        return 0;
    }

    while (1)
    {
        TString runnumber;
        runnumber.ReadLine(fin);
        if (!fin)
            break;

        TString query(Form("UPDATE RunProcessStatus SET %s=Now()", column.Data()));

        if (column.Contains("CaCo"))
            query+=Form(", fCaCoFileFound=%d", atoi(runnumber));

        query+=Form(" WHERE fRunNumber=%d and %s!='1970-01-01 00:00:00'", atoi(runnumber), column.Data());

        cout << "q2: " << query << endl;

        res = serv.Query(query);
        if (!res)
        {
            cout << "updating (setting " << column.Data() << " = Now()) for run# " << atoi(runnumber) << ") didn't work " << endl;
            return 0;
        }
        delete res;
    }

    return 1;
}


