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

/////////////////////////////////////////////////////////////////////////////
//
// insertdataset.C
// ===============
//
// This macro inserts datasets into the database.
// If a new dataset file has been stored in the dataset directory, the
// information file is read by a script and the information is inserted with
// this macro into the database in the tables DataSets and
// DataSetProcessStatus, where in the information about datasets is stored.
//
// Usage:
//   .x insertdataset.C+("number","source,"wobble","comment",kTRUE)
// The first argument is the dataset number, the second is giving the source
// name, the third the observation mode (wobble/on-off), the fourth a comment
// about the dataset. This arguments are extracted by a script from the
// dataset file.
// The last 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.
//
// 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 <fstream>

#include <TEnv.h>

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

using namespace std;

Bool_t ExistStr(MSQLServer &serv, const char *column, const char *table, const char *test)
{
    TString query(Form("SELECT %s FROM %s WHERE %s='%s'", column, table, column, test));
    TSQLResult *res = serv.Query(query);
    if (!res)
        return kFALSE;

    Bool_t rc = kFALSE;

    TSQLRow *row=res->Next();
    if (row && (*row)[0])
        rc=kTRUE;

    delete res;
    return rc;
}

//get key of a name
// insert value, if it is not yet existing
Int_t QueryNameKEY(MSQLServer &serv, Bool_t dummy, const char *col, const char *name, Bool_t insert=kTRUE)
{
    TString query;

    query = Form("SELECT f%sKEY FROM %s WHERE f%sName='%s'", col, col, col, name);
    TSQLResult *res = serv.Query(query);
    if (!res)
        return -1;

    TSQLRow *row=res->Next();

    Int_t rc = row && (*row)[0] ? atoi((*row)[0]) : -1;

    delete res;

    if (rc>=0)
        return rc;

    if (!insert)
        return -1;

    query = Form("INSERT %s (f%sName) VALUES (\"%s\");", col, col, name);

    if (dummy)
    {
        cout << query << endl;
        return 0;
    }

    res=serv.Query(query);
    if (!res)
        return -1;

    delete res;

    Int_t key = QueryNameKEY(serv, dummy, col, name, kFALSE);
    if (key>0)
    {
        cout << "New " << col << ": " << name << endl;
        return key;
    }

    cout << "ERROR: " << query << endl;
    return kFALSE;
}

int insertdataset(TString number, TString source, TString wobble, TString comment, Bool_t dummy=kTRUE)
{
    TEnv env("sql.rc");

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

    //get source key
    Int_t sourcekey = QueryNameKEY(serv, dummy, "Source", source.Data(), kFALSE);
    if (sourcekey<0)
    {
        cout << "Error - could not get sourcename from DB -> " << flush;
        cout << "maybe you have the wrong sourcename in your datasetfile" << endl;
        return 2;
    }

    cout << "no:" << number << endl;

    //if dataset is not yet in database, insert the information
    if (!ExistStr(serv, "fDataSetNumber", "DataSets", number.Data())) // Form("%d", number)
    {
        TString query=Form("INSERT DataSets SET fDataSetNumber='%s', "
                   " fSourceKEY=%d, fWobble='%s', fComment='%s' ",
                   number.Data(), sourcekey, wobble.Data(), comment.Data());

        if (dummy)
        {
            cout << query << endl;
            return 0;
        }

        TSQLResult *res = serv.Query(query);
        if (!res)
        {
            cout << "Error - could not insert dataset" << endl;
            return 2;
        }
        delete res;

        //add also entry in the table DataSetProcessStatus
        query=Form("INSERT DataSetProcessStatus SET fDataSetNumber='%s', "
                   " fDataSetInserted=Now() ",
                   number.Data());

        res = serv.Query(query);
        if (!res)
        {
            cout << "Error - could not insert dataset" << endl;
            return 2;
        }
        delete res;
    }
    else
    {
        cout << number << " already exists... " << endl;
        return 3;
    }

    return 1;
}


