/* ======================================================================== *\
!
! *
! * 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>
!
!   Copyright: MAGIC Software Development, 2000-2006
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// filloptical.C
// =============
//
// This macro is used to read the files from KVA containing the results from
// the optical observations.
// Remark: Running it from the commandline looks like this:
//   root -q -l -b filloptical.C+\(\"filename\"\,kFALSE\) 
//
// Make sure, that database and password are corretly set.
//
// Returns 0 in case of failure and 1 in case of success.
//
///////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>

#include <TVector3.h>

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

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

#include "MDirIter.h"
#include "MSQLServer.h"
#include "MSQLMagic.h"

#include "MTime.h"
#include "MObservatory.h"
#include "MAstroSky2Local.h"

using namespace std;

//
// insert the entries from this optical data file into the db
//
int process(MSQLMagic &serv, TString fname)
{
    ifstream fin(fname);
    if (!fin)
    {
        cout << "Could not open file " << fname << endl;
        return 0;
    }

    TRegexp regexp("^20[0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].*$", kFALSE);

    Int_t numexp=0;
    Int_t numstars=0;

    TString timestamp;
    TString exposure;
    TString fitsfile;
    TString object;
    TString skylevel;
    TString fwhm;
    TString aperturer;
    TString mag;
    TString magerr;
    TString status;
    TString query;
    TString select;
    TString telescope;
    TString telname;
    TString ccd;
    TString filterband;
    TString filter;
    TString band;
    Double_t ra=0;
    Double_t dec=0;
    Double_t zd=0;
    MTime t;
    MObservatory obs(MObservatory::kMagic1);
    TVector3 v;

    cout << fname << endl;

    if (fname(TRegexp("20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_R[_]?[12]?[.]instr", kFALSE)).IsNull())
    {
        cout << "Found not valid file: " << fname << endl;
        return 2;
    }

    while (1)
    {
        TString line;
        line.ReadLine(fin);
        if (!fin)
            break;

        if (line.IsNull())
            continue;

        TObjArray *arr = line.Tokenize("  ");

        if (line=="KVA_Celestron_ST8  KVA_Celestron_R" ||
            line=="Tuorla_ST1001E  Tuorla_R")
        {
            if (arr->GetEntries()!=2)
            {
                cout << "WARNING: Telescopeline with less or more than 2 arguments found " << endl;
                return 2;
            }
            telescope=(*arr)[0]->GetName();
            telname=telescope(0,telescope.First('_'));
            ccd=telescope(telescope.Last('_')+1, telescope.Length());
            filterband=(*arr)[1]->GetName();
            filter=filterband(0,filterband.Last('_'));
            band=filterband(filterband.Last('_')+1, filterband.Length());
            continue;
        }

        if (!line(regexp).IsNull())
        {
            if (arr->GetEntries()!=4)
            {
                cout << "WARNING: Timestampline with less or more than 4 arguments found " << endl;
                return 2;
            }
            numexp+=1;
            numstars=0;
            timestamp =Form("%s %s", (*arr)[0]->GetName(),(*arr)[1]->GetName());

            exposure   = (*arr)[2]->GetName();
            fitsfile = (*arr)[3]->GetName();
            t.SetSqlDateTime(timestamp.Data());
            continue;
        }
        else
        {
            if (arr->GetEntries()!=8)
            {
                cout << "WARNING: Objectline with less or more than 8 arguments found " << endl;
                cout << line << endl;
                return 2;
            }

            if (numstars==0)
            {
                select="SELECT fRightAscension, fDeclination FROM Object WHERE ";
                select+=Form("fObjectName='%s/BL'", (*arr)[0]->GetName());

                TSQLResult *res = serv.Query(select);
                if (!res)
                    return 2;

                TSQLRow *row=res->Next();

                if (!row)
                {
                    cout << "Query failed: " << select << endl;
                    continue;
                }

                ra =(*row)[0]?atof((*row)[0]):0;
                dec=(*row)[1]?atof((*row)[1]):0;
                delete res;

                v.SetMagThetaPhi(1, TMath::Pi()/2-(dec*TMath::DegToRad()), ra*TMath::DegToRad()*15);
                v *= MAstroSky2Local(t, obs);

                zd = v.Theta()*TMath::RadToDeg();

            }

            object= Form("%s/%s", (*arr)[0]->GetName(),(*arr)[1]->GetName());
            skylevel   = (*arr)[2]->GetName();
            if (skylevel.Contains("-"))
                skylevel="NULL";
            fwhm = (*arr)[3]->GetName();
            if (fwhm.Contains("-") || !fwhm.IsFloat())
                fwhm="NULL";
            aperturer = (*arr)[4]->GetName();
            mag = (*arr)[5]->GetName();
            if (!mag.IsFloat())
                mag="NULL";
            magerr = (*arr)[6]->GetName();
            if (!magerr.IsFloat())
                magerr="NULL";
            status = (*arr)[7]->GetName();
            numstars+=1;
        }
        delete arr;

        if (numstars!=0)
        {
            /*
            cout << numexp << "th exposure: star # " << numstars << endl;
            cout << " timestamp: " << timestamp << endl;
            cout << " exposure : " << exposure  << endl;
            cout << " fitsfile : " << fitsfile  << endl;
            cout << " object   : " << object << endl;
            cout << " skylevel : " << skylevel  << endl;
            cout << " fwhm     : " << fwhm      << endl;
            cout << " aperturer: " << aperturer << endl;
            cout << " mag      : " << mag << " +/- " << magerr << endl;
            cout << " status   : " << status    << endl << endl;
            */
            Int_t statuskey   = serv.QueryKeyOfName("Status", status.Data());
            Int_t objectkey   = serv.QueryKeyOfName("Object", object.Data());
            Int_t fitsfilekey = serv.QueryKeyOfName("FitsFile", fitsfile.Data());
            Int_t telkey      = serv.QueryKeyOfName("Telescope", telname.Data());
            Int_t ccdkey      = serv.QueryKeyOfName("CCD", ccd.Data());
            Int_t bandkey     = serv.QueryKeyOfName("Band", band.Data());
            Int_t filterkey   = serv.QueryKeyOfName("Filter", filter.Data());

            query=Form("fTimeStamp='%s', fExposure=%s, fFitsFileKEY=%d, "
                       "fObjectKEY=%d, fSkyLevel=%s, fFWHM=%s, "
                       "fApertureRadius=%s, fInstrumentalMag=%s, "
                       "fInstrumentalMagErr=%s, fStatusKEY=%d, fCCDKEY=%d, "
                       "fFilterKEY=%d, fTelescopeKEY=%d, fBandKEY=%d, "
                       "fZenithDistance=",
                       timestamp.Data(), exposure.Data(), fitsfilekey,
                       objectkey, skylevel.Data(), fwhm.Data(),
                       aperturer.Data(), mag.Data(), magerr.Data(),
                       statuskey, ccdkey, filterkey, telkey, bandkey);

            if (ra==0 || dec==0)
                query+="NULL";
            else
                query+=Form("%.1f", zd);

            if (serv.Insert("OpticalData", query)==kFALSE)
                return 2;

        }

    }

    cout << fname(TRegexp("20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_.*_R[_]?[12]?[.]instr", kFALSE))
        << ": " << setw(2) << numexp << " exposures, " <<  setw(2) << numstars << " stars" << endl;

    return 1;
}

// --------------------------------------------------------------------------
//
// loop over all files in this path
//
int filloptical(TString path, Bool_t dummy=kTRUE)
{
    TEnv env("sql.rc");

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

    serv.SetIsDummy(dummy);

    cout << endl;
    cout << "filloptical" << endl;
    cout << "-----------" << endl;
    cout << endl;
    cout << "Connected to " << serv.GetName() << endl;
    cout << "Search Path: " << path << endl;
    cout << endl;

    //get all runbook files in path
    if (path.EndsWith(".instr"))
        return process(serv, path);

    //fill entries for each optical data file
    MDirIter Next(path, "20[0-9][0-9]_[0-1][0-9]_[0-3][0-9]_*_R[_]?[12]?[.]instr", -1);
    while (1)
    {
        TString name = Next();
        if (name.IsNull())
            break;

        if (!process(serv, name))
            return 0;
    }

    return 1;
}
