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

/////////////////////////////////////////////////////////////////////////////
//
// fillsinope.C
// ============
//
// This macro is used to read the sinope output files sinope*.txt
//
// Usage:
//   .x fillsignal.C(runnumber, kTRUE)
//
// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
// switched on and nothing will be written into the database. This is usefull
// for tests.
//
// Remark: Running it from the commandline looks like this:
//   root -q -l -b fillsinope.C+\(runno\,kFALSE\) 2>&1 | tee fillsinope.log
//
// Make sure, that database and password are corretly set in a resource
// file called sql.rc and the resource file is found.
//
// Returns 0 in case of failure and 1 in case of success.
//
/////////////////////////////////////////////////////////////////////////////
#include <iostream>

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

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

#include "MSQLServer.h"

#include "MStatusArray.h"
#include "MHCamera.h"

using namespace std;

Bool_t ExistStr(MSQLServer &serv, const char *column, const char *table, const char *test)
{
    TString query(Form("SELECT %s FROM %s WHERE %s='%s'", column, table, column, test));
    TSQLResult *res = serv.Query(query);
    if (!res)
    {
        cout << "ERROR - Query failed: " << query << endl;
        return kFALSE;
    }

    Bool_t rc = kFALSE;

    TSQLRow *row=res->Next();
    if (row && (*row)[0])
        rc=kTRUE;

    delete res;
    return rc;
}

int Process(MSQLServer &serv, TString fname, Int_t runno, Bool_t cal, Bool_t dummy)
{
    TEnv env(fname);

    TString query="UPDATE DataCheck SET ";

    TString values[9] = { "Events" , "HasSignal" , "HasPedestal" , "PositionSignal" , "PositionFWHM" , "PositionAsym" , "HeightSignal" , "HeightFWHM" , "HeightAsym" };

    TString str;
    for (Int_t i=0 ; i<9 ; i++)
    {
//        cout << "value: " << values[i] << endl;
//        cout << "str: " << str << endl;
        str = env.GetValue(values[i], "");
        if (str.IsNull())
            continue;

        if (cal)
            values[i]+="InterLaced";
        values[i]+="='";
        values[i]+=str;

        if (i!=0)
            query+=", ";
        query+=" f";
        query+=values[i];
        query+="' ";

        cout << "value: " << values[i] << endl;

    }

    query+=Form(" WHERE fRunNumber=%d", runno);

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

int fillsinope(Int_t runno, TString datapath, Bool_t dummy=kTRUE)
{
    TEnv env("sql.rc");

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

    cout << "fillsignal" << endl;
    cout << "----------" << endl;
    cout << endl;
    cout << "Connected to " << serv.GetName() << endl;
    cout << "Run: " << runno << endl;
    cout << endl;

    TString query(Form("SELECT DATE_FORMAT(ADDDATE(fRunStart, Interval 13 HOUR), '%%Y/%%m/%%d') FROM RunData WHERE fRunNumber=%d",
                       runno));

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

    TSQLRow *row = 0;
    row = res->Next();
    TString date=(*row)[0];
    cout << "date: " << date << endl;
    delete res;

    if (!ExistStr(serv, "fRunNumber", "DataCheck", Form("%d", runno)))
    {
        query=Form("INSERT DataCheck SET fRunNumber=%d", runno);

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

    TString fname(Form("%s/sinope/%s/sinope-dat%08d.txt",
                       datapath.Data(), date.Data(), runno));
    cout << "file: " << fname << endl;
    TString fnamecal(Form("%s/sinope/%s/sinope-cal%08d.txt",
                        datapath.Data(), date.Data(), runno));
    cout << "file-cal: " << fnamecal << endl;

    Int_t rc=0;
    rc=Process(serv, fname, runno, kFALSE, dummy);
    if (rc==0)
        return rc;

    rc=Process(serv, fnamecal, runno, kTRUE, dummy);
    return rc;
}
