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

/////////////////////////////////////////////////////////////////////////////
//
// InsertDataset.C
// ===============
//
/////////////////////////////////////////////////////////////////////////////

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

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

    Int_t sourcekey = QueryNameKEY(serv, dummy, "Source", source.Data());
    if (sourcekey<0)
    {
        cout << "Error - could not get sourcename from DB" << endl;
        return 0;
    }

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

    if (!ExistStr(serv, "fDataSetNumber", "DataSets", number.Data())) // Form("%d", number)
    {
        TString query=Form("INSERT DataSets SET fDataSetNumber='%s', "
                   " fSourceKEY=%d, fWobble='%s' ",
                   number.Data(), sourcekey, wobble.Data());

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

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


        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 0;
        }
        delete res;
    }
    else
    {
        cout << number << " already exists... " << endl;
        return 0;
    }

    return 1;
}


