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

/////////////////////////////////////////////////////////////////////////////
//
// filldotraw.C
// ============
//
// This macro is used to read a merpped raw data file or a raw data file
// directly. The descision is taken by the file-name extension (".root" or
// ".raw")
//
// Usage:
//   .x filldotraw.C("/data/MAGIC/Period014/filename.raw", 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.
//
// Filling the database is done with 'UPADTE' for _all_ columns
// matching the Run-Number!
//
// 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 filldotraw.C+\(\"filename\"\,kFALSE\) 2>&1 | tee filldotraw.log
//
// Make sure, that database and password are corretly set in the macro.
//
// Returns 0 in case of failure and 1 in case of success.
//
/////////////////////////////////////////////////////////////////////////////

#include <fstream>
#include <iostream>

#include <TFile.h>
#include <TTree.h>

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

#include "MSQLServer.h"
#include "MRawRunHeader.h"

using namespace std;

Int_t MagicNumber(MSQLServer &serv, const MRawRunHeader &h)
{
    TString query(Form("SELECT fMagicNumberKEY FROM MyMagic.MagicNumber WHERE fMagicNumber=%d",
                       h.GetMagicNumber()));

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

    TSQLRow *row = res->Next();
    if (!row)
    {
        cout << "ERROR - No result from query: " << query << endl;
        return -1;
    }

    return atoi((*row)[0]);
}

Bool_t ReadRaw(TString fname, MRawRunHeader &h)
{
    ifstream fin(fname);
    if (!fin)
    {
        cout << "ERROR - Couldn't open file " << fname << endl;
        return kFALSE;
    }

    if (!h.ReadEvt(fin))
    {
        cout << "ERROR - Reading header from file " << fname << endl;
        return kFALSE;
    }
    return kTRUE;
}

Bool_t ReadRoot(TString fname, MRawRunHeader *h)
{
    TFile file(fname, "READ");
    if (file.IsZombie())
    {
        cout << "ERROR - Cannot open file " << fname << endl;
        return kFALSE;
    }

    TTree *t = (TTree*)file.Get("RunHeaders");
    if (!t)
    {
        cout << "ERROR - Tree RunHeaders not found." << endl;
        return kFALSE;
    }

    t->SetBranchAddress("MRawRunHeader.", &h);
    t->GetEntry(0);

    return kTRUE;
}

Bool_t Process(MSQLServer &serv, TString fname, Bool_t dummy)
{
    MRawRunHeader h;

    if (fname.EndsWith(".root"))
        ReadRoot(fname, &h);
    if (fname.EndsWith(".raw"))
        ReadRaw(fname, h);

    if (dummy)
    {
        h.Print("header");
        return kTRUE;
    }

    const Int_t key = MagicNumber(serv, h);
    if (key<0)
        return kFALSE;

    TString query(Form("UPDATE MyMagic.RunData SET fMagicNumberKEY=%d, fFormatVersion=%d WHERE fRunNumber=%d",
                       key, h.GetFormatVersion(), h.GetRunNumber()));

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

    return kTRUE;
}

void filldotraw(TString fname, Bool_t dummy=kTRUE)
{
    MSQLServer serv("mysql://hercules:d99swMT!@localhost");
    if (!serv.IsConnected())
    {
        cout << "ERROR - Connection to database failed." << endl;
        return;
    }

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

    cout << (Process(serv, fname, dummy) ? "Done." : "failed!") << endl << endl;
}
