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

/////////////////////////////////////////////////////////////////////////////
//
// fillsignal.C
// ============
//
// This macro is used to read the calibration-/callisto-output files
// signal00000.root.
//
// From this file the Mean PedRms for the inner and outer camera is extracted.
//
// Usage:
//   .x fillsignal.C("/data/MAGIC/Period014/signal00000.root", 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.
//
// The macro can also be run without ACLiC but this is a lot slower...
//
// Remark: Running it from the commandline looks like this:
//   root -q -l -b fillsignal.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillsignal.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 "MSQLServer.h"

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

using namespace std;

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 = (MStatusArray*)file.Get("MStatusDisplay");
    if (!arr)
    {
        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
        return 0;
    }

    MHCamera *cam = (MHCamera*)arr->FindObjectInCanvas("PedRMS;avg", "MHCamera", "PedRMS");
    if (!cam)
    {
        cout << "WARNING - Reading of PedRMS;avg failed." << endl;
        return 0;
    }

    TArrayI inner(1);
    inner[0] = 0;

    TArrayI outer(1);
    outer[0] = 1;

    Int_t s0[] = { 1, 2, 3, 4, 5, 6 };

    Stat_t meani = cam->GetMeanSectors(TArrayI(6, s0), inner);
    Stat_t meano = cam->GetMeanSectors(TArrayI(6, s0), outer);

    if (meani<0 || meano<0)
    {
        cout << "WARNING - MeanPedRMS inner or outer < 0 " << endl;
        cout << "MeanPedRMS inner " << meani << endl;
        cout << "MeanPedRMS outer " << meano << endl;
        return 0;
    }

    meani = TMath::Nint(meani*100)/100.;
    meano = TMath::Nint(meano*100)/100.;

    TString sequence = fname(TRegexp("signal[0-9]+[.]root$"));
    if (sequence.IsNull())
    {
        cout << "WARNING - Sequ# empty" << endl;
        cout << "Sequ# " << sequence << endl;
        return 0;
    }

    Int_t seq = atoi(sequence.Data()+6);
    TString meaninner=Form("%6.2f", meani);
    TString meanouter=Form("%6.2f", meano);

    cout << "Sequence #" << seq << endl;
    cout << "  Mean Ped RMS inner [phe] " << meaninner << endl;
    cout << "  Mean Ped RMS outer [phe] " << meanouter << endl;

    TString query = Form("UPDATE Calibration SET fMeanPedRmsInner=%s, "
                         " fMeanPedRmsOuter=%s WHERE fSequenceFirst='%d' ",
                         meaninner.Data(), meanouter.Data(), seq);

    if (dummy)
        return 0;

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

    return 1;
}

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

    return Process(serv, fname, dummy);
}
