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

/////////////////////////////////////////////////////////////////////////////
//
// GetDoList.C
// ===========
//
/////////////////////////////////////////////////////////////////////////////

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

#include <TEnv.h>
#include <TObjString.h>
#include <TList.h>
#include <TSystem.h>

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

using namespace std;


int getdolist(TString table, TString column, TString date, TString listpath)
{
    TEnv env("sql.rc");

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

    TEnv rc("steps.rc");

    TString needs  = rc.GetValue(table+"."+column+".Needs", "");
    cout << "Needs: " << needs  << endl;

    TList l;

    while (!needs.IsNull())
    {
        needs = needs.Strip(TString::kBoth);

        Int_t idx = needs.First(' ');
        if (idx<0)
            idx = needs.Length();

        TString need = needs(0, idx);
        needs.Remove(0, idx);
        l.Add(new TObjString(need));
    }

    TString query(Form("SELECT %s.%s FROM %s",
                       table.Data(), rc.GetValue(table+".Primary", ""),
                       table.Data()));

    if (date!="NULL" && rc.GetValue(table+".TimerTable", "")!="")
        query+=Form(" left join %s on %s.%s=%s.%s ",
                    rc.GetValue(table+".TimerTable", ""), table.Data(),
                    rc.GetValue(table+".Primary", ""),
                    rc.GetValue(table+".TimerTable", ""),
                    rc.GetValue(table+".Primary", ""));
    query+=Form(" WHERE ISNULL(%s)", column.Data());

    TIter Next(&l);
    TObject *o=0;
    while ((o=Next()))
        query+=Form(" AND NOT ISNULL(%s)", o->GetName());

    if (date!="NULL")
    {
        if (rc.GetValue(table+".TimerTable", "")!="")
        {
            TString day=date+" 13:00:00";
            query+=Form(" AND (fRunStart>ADDDATE(\"%s\", INTERVAL -1 DAY) AND fRunStart<\"%s\")",
                        day.Data(), day.Data());
        }
        else
            query+=Form(" AND %s=%s ", rc.GetValue(table+".Primary", ""), date.Data());
    }

    query+=Form(" ORDER BY %s.%s DESC ", table.Data(), rc.GetValue(table+".Primary", ""));

    if (table=="RunProcessStatus")
        query+="LIMIT 0, 500";

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

    TSQLResult *res = serv.Query(query);
    if (!res)
    {
        cout << "ERROR - Query failed: " << query << endl;
        return 0;
    }


    TString filename;
    TSQLRow *row=0;

    if ((table=="SequenceProcessStatus" && column=="fCallisto")      ||
        (table=="SequenceProcessStatus" && column=="fStar")          ||
        (table=="RunProcessStatus"      && column=="fDataCheckDone") ||
        (table=="DataSetProcessStatus"  && column=="fGanymed"))
    {
        while ((row = res->Next()))
        {
            filename=Form("%s/ToDo-%s-%s-%s.txt", listpath.Data(), table.Data(), column.Data(), (*row)[0]);
            gSystem->Unlink(filename);
            ofstream fout(filename, ios::app);
            if (!fout)
            {
                cout << "ERROR - Cannot open file " << filename << endl;
                return 0;
            }
            fout << (*row)[0] << endl;
        }
    }
    else
    {
        filename=Form("%s/ToDo-%s-%s.txt", listpath.Data(), table.Data(), column.Data());
        ofstream fout(filename, ios::app);
        if (!fout)
        {
            cout << "ERROR - Cannot open file " << filename << endl;
            return 0;
        }

        while ((row = res->Next()))
            fout << (*row)[0] << endl;
    }

    delete res;

    return 1;
}


