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

/////////////////////////////////////////////////////////////////////////////
//
// fillstar.C
// ==========
//
// This macro is used to read the star-output files.
// These files are automatically called star00000.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 <TEnv.h>
#include <TRegexp.h>

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

#include "MSQLServer.h"

#include "MStatusArray.h"
#include "MGeomCamMagic.h"
#include "MBadPixelsCam.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");

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

    TProfile *h1 = (TProfile*)arr.FindObjectInCanvas("RingBroadening", "TProfile", "MHMuonPar");
    if (!h1)
    {
        cout << "WARNING - Reading of RingBroadening failed." << endl;
        return 0;
    }

    Float_t psf = (h1->Integral(5, 14) - 0.759)/0.027;
    psf = TMath::Nint(psf*10)/10.;
    TString PSF = Form("%5.1f", psf);

    TProfile *h2 = (TProfile*)arr.FindObjectInCanvas("SizeVsRadius", "TProfile", "MHMuonPar");
    if (!h1)
    {
        cout << "WARNING - Reading of SizeVsRadius failed." << endl;
        return 0;
    }

    Float_t integral = h2->Integral(5, 14);
    Float_t integralmc = -33.0*psf + 10517;
    Float_t ratiodatamc = (integral/integralmc)*100;
    TString ratio = Form("%5.1f", ratiodatamc);


    TH1 *h = (TH1*)arr.FindObjectInCanvas("Islands", "TH1F", "MHImagePar");
    if (!h)
    {
        cout << "WARNING - Reading of Islands failed." << endl;
        return 0;
    }

    Float_t quality = h->GetMean();
    quality = TMath::Nint(quality*10)/10.;
    TString islands = Form("%5.1f", quality);

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

    Int_t seq = atoi(sequence.Data()+5);

    cout << "Sequence #" << seq << endl;
    cout << "  PSF [mm]       " << Form("%5.1f", psf)         << endl;
    cout << "  Island Quality " << Form("%5.1f", quality)     << endl;
    cout << "  Ratio [%]      " << Form("%5.1f", ratiodatamc) << endl;

    TString query;
    if (!ExistStr(serv, "fSequenceFirst", "MyMagic.Star", seq))
    {
        query = Form("INSERT MyMagic.Star SET"
                     " fSequenceFirst=%d,"
                     " fMeanNumberIslands=%s, "
                     " fRatio=%s, "
                     " fPSF=%s ",
                     seq, islands.Data(), ratio.Data(), PSF.Data());
    }
    else
    {
        query = Form("UPDATE MyMagic.Star SET"
                     " fMeanNumberIslands=%s, "
                     " fRatio=%s, "
                     " fPSF=%s "
                     " WHERE fSequenceFirst=%d ",
                     islands.Data(), ratio.Data(), PSF.Data(), seq);
    }

    if (dummy)
        return 0;

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

    return 1;
}

int fillstar(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 << "fillstar" << endl;
    cout << "---------" << endl;
    cout << endl;
    cout << "Connected to " << serv.GetName() << endl;
    cout << "File: " << fname << endl;
    cout << endl;

    return Process(serv, fname, dummy);
}
