/* ======================================================================== *\
!
! *
! * 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 <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 "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");
    if (!file.IsOpen())
    {
        cout << "ERROR - Could not find file " << fname << endl;
        return 0;
    }


    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;
    }

    //spline
//    Float_t psf = (h1->Integral(5, 14) - 0.818)/0.0276;
    //df
    Float_t psf = (h1->Integral(5, 14) - 0.7868)/0.0254;
    psf = TMath::Nint(psf*10)/10.;
    TString PSF = Form("%5.1f", psf);
    Int_t   num = (int)h1->GetEntries();

    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);
    //spline
//    Float_t integralmc = -36.06*psf + 11023;
    //df
    Float_t integralmc = -29.3*psf + 10167;
    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("%6.2f", quality);

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

    Float_t effon = h->Integral();
    Float_t mrate  = num/effon;
    mrate = TMath::Nint(mrate*100)/100.;
    TString muonrate = Form("%6.2f", mrate);
    Int_t effontime = TMath::Nint(effon);

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

    Int_t numevents = (int)h->GetEntries();
    Int_t datarate  = (int)(numevents/effon);

    TGraph *g = (TGraph*)arr.FindObjectInCanvas("Humidity", "TGraph", "MHWeather");
    if (!g)
    {
        cout << "WARNING - Reading of Humidity failed." << endl;
        return 0;
    }

    Double_t max = TMath::MaxElement(g->GetN(), g->GetY());
    TString maxhum = Form("%6.1f", max);


    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]              " << PSF       << endl;
    cout << "  Island Quality        " << islands   << endl;
    cout << "  Ratio [%]             " << ratio     << endl;
    cout << "  Muon Number           " << num       << endl;
    cout << "  EffOnTime [s]         " << effontime << endl;
    cout << "  Muon Rate [Hz]        " << muonrate  << endl;
    cout << "  # of Events           " << numevents << endl;
    cout << "  Rate after ImgCl [Hz] " << datarate  << endl;
    cout << "  Maximum Humidity [%]  " << maxhum    << endl;

    TString query;
    if (!ExistStr(serv, "fSequenceFirst", "Star", seq))
    {
        query = Form("INSERT Star SET"
                     " fSequenceFirst=%d,"
                     " fMeanNumberIslands=%s, "
                     " fRatio=%s, "
                     " fMuonNumber=%d, "
                     " fEffOnTime=%d, "
                     " fMuonRate=%s, "
                     " fPSF=%s, "
                     " fDataRate=%d, "
                     " fMaxHumidity=%s ",
                     seq, islands.Data(), ratio.Data(),
                     num, effontime,
                     muonrate.Data(), PSF.Data(),
                     datarate, maxhum.Data());
    }
    else
    {
        query = Form("UPDATE Star SET"
                     " fMeanNumberIslands=%s, "
                     " fRatio=%s, "
                     " fMuonNumber=%d, "
                     " fEffOnTime=%d, "
                     " fMuonRate=%s, "
                     " fPSF=%s, "
                     " fDataRate=%d, "
                     " fMaxHumidity=%s "
                     " WHERE fSequenceFirst=%d ",
                     islands.Data(), ratio.Data(),
                     num, effontime,
                     muonrate.Data(), PSF.Data(),
                     datarate, maxhum.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);
}
