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

/////////////////////////////////////////////////////////////////////////////
//
// fillganymed.C
// =============
//
// This macro is used to read the ganymed-output files.
// These files are automatically called ganymed00000.root.
//
// 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 <iomanip>

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

#include <TH1.h>
#include <TGraph.h>
#include <TProfile.h>
#include <TFile.h>
#include <TSQLResult.h>
#include <TSQLRow.h>

#include "MSQLServer.h"

#include "MStatusArray.h"
#include "MGeomCamMagic.h"
#include "MAlphaFitter.h"

using namespace std;

// --------------------------------------------------------------------------
//
// Checks whether an entry is already existing
//
Bool_t ExistStr(MSQLServer &serv, const char *column, const char *table, Int_t test)
{
    TString query(Form("SELECT %s FROM %s WHERE %s='%d'", column, table, column, test));
    TSQLResult *res = serv.Query(query);
    if (!res)
        return kFALSE;

    TSQLRow *row;

    Bool_t rc = kFALSE;
    while ((row=res->Next()))
    {
        if ((*row)[0])
        {
            rc = kTRUE;
            break;
        }
    }

    delete res;

    return rc;
}


int Process(MSQLServer &serv, TString fname, Bool_t dummy)
{
    TFile file(fname, "READ");
    if (!file.IsOpen())
    {
        cout << "ERROR - Could not find file " << fname << endl;
        return 0;
    }

    MAlphaFitter *fit;
    file.GetObject("MAlphaFitter", fit);

    if (!fit)
    {
        cout << "WARNING - Reading of MAlphaFitter failed." << endl;
        return 0;
    }

    Double_t exc = fit->GetEventsExcess();
    Double_t sig = fit->GetEventsSignal();
    Double_t bgd = fit->GetEventsBackground();
    Double_t S   = fit->GetSignificance();
    Double_t f   = fit->GetScaleFactor();

    MStatusArray arr;
    if (arr.Read()<=0)
    {
        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
        return 0;
    }

    TH1D *vstime = (TH1D*)arr.FindObjectInCanvas("Theta",  "TH1D", "OnTime");
    if (!vstime)
    {
        cout << "WARNING - Reading of Theta failed." << endl;
        return kFALSE;
    }


    Double_t tm = vstime->Integral();

    TString dataset = fname(TRegexp("ganymed[0-9]+[.]root$"));
    if (dataset.IsNull())
    {
        cout << "WARNING - Could get dataset# from filename: " << fname << endl;
        return 0;
    }

    Int_t ds = atoi(dataset.Data()+8);

    cout << "Dataset #" << ds << endl;
    cout << "  Excess     Events:  " << exc << endl;
    cout << "  Background Events:  " << bgd << endl;
    cout << "  Signal     Events:  " << sig << endl;
    cout << "  Significance:       " << S   << endl;
    cout << "  Scale Factor:       " << f   << endl;
    cout << "  Total eff. on-time: " << tm << "s = " << tm/3600. << "h" << endl;

    cout << "  Excess       Rate:  " << exc*60/tm << " evts/min"  << endl;
    cout << "  Background   Rate:  " << bgd*60/tm << " evts/min"  << endl;
    cout << "  Significance Rate:  " << S/TMath::Sqrt(tm/3600.) << " sigma/sqrt(h)" << endl;


    TString query;
    if (!ExistStr(serv, "fDataSetNumber", "Ganymed", ds))
    {
        query = Form("INSERT Ganymed SET"
                     " fDataSetNumber=%d,"
                     " fExcessEvents=%f, "
                     " fBackgroundEvents=%f, "
                     " fSignalEvents=%f, "
                     " fSignificance=%f, "
                     " fScaleFactor=%f, "
                     " fEffOnTime=%f, "
                     " fExcessRate=%f, "
                     " fBackgroundRate=%f, "
                     " fSignificanceRate=%f ",
                     ds, exc, bgd, sig, S, f, tm,
                     exc*60/tm, bgd*60/tm,
                     S/TMath::Sqrt(tm/3600));
    }
    else
    {
        query = Form("UPDATE Ganymed SET"
                     " fExcessEvents=%f, "
                     " fBackgroundEvents=%f, "
                     " fSignalEvents=%f, "
                     " fSignificance=%f, "
                     " fScaleFactor=%f, "
                     " fEffOnTime=%f, "
                     " fExcessRate=%f, "
                     " fBackgroundRate=%f, "
                     " fSignificanceRate=%f ",
                     " WHERE fDataSetNumber=%d ",
                     exc, bgd, sig, S, f, tm,
                     exc*60/tm, bgd*60/tm,
                     S/TMath::Sqrt(tm/3600), ds);
    }

    if (dummy)
        return 0;

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

int fillganymed(TString fname, Bool_t dummy=kTRUE)
{
    TEnv env("sql.rc");

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

    cout << "fillganymed" << endl;
    cout << "-----------" << endl;
    cout << endl;
    cout << "Connected to " << serv.GetName() << endl;
    cout << "File: " << fname << endl;
    cout << endl;

    return Process(serv, fname, dummy);
}
