//
// C/C++ headers
//
#include <iostream>
#include <sstream>
//
// ROOT headers
//
#include <TString.h>
#include <TSQLServer.h>
#include <TFile.h>
#include <TSystem.h>
//
// Detector's package headers
//
#include <GLTables.h>
//
using namespace std;
//
//
//
#include <DarthVaderVerl2.h>
//
// Usage subroutine
//
void r2d2usage(){
  printf("\nUsage:\n");
  printf("\n DarthVader [-h | --help] [--version] [-idRun ID_RUN] [-filename filename]\n");
  printf("\n            [-host host] [-user username] [-psw password] \n");
  printf("\n --version       print informations about compilation and exit\n");
  printf("\n -h | --help     print this help and exit \n");
  printf("\n -v | --verbose  be verbose [default: print nothing on STDOUT]\n");
  printf("\n -idRun          ID_RUN: ID number of the run \n");
  printf("\n -filename       output yoda filename \n");
  printf("\n -host           name for the host [default = mysql://localhost/pamelaprod]\n");
  printf("\n -user           username for the DB [default = anonymous] \n");
  printf("\n -psw            password for the DB [default = \"\"]\n");
  printf("\nExamples: \n");
  printf("\n R2-D2 -idRun 1085 \n");
  printf("\n R2-D2 -filename DW_050208_00900.root \n");
  printf("\n R2-D2 -idRun 1085 -filename DW_050208_00900.root \n");
};
//
// Here the main
//
int main(int numinp, char *inps[]){
  //
  // Variables booking
  //
  TString message;
  Int_t error = 0;
  //
  ULong64_t run = 0ULL;
  //
  TString filename = "";
  //
  TSQLServer *dbc = 0;
  TString host = "mysql://localhost/pamelaprod";
  TString user = "anonymous";
  TString psw = "";
  //
  //
  // Checking input parameters
  //
  Int_t i = 0;
  if ( numinp > 1 ){
    while ( i < numinp ){
      if ( !strcmp(inps[i],"--version") ){
	DarthVaderInfo(true);
	exit(0);
      };
      if ( !strcmp(inps[i],"-h") || !strcmp(inps[i],"--help") ){
	r2d2usage();
	exit(0);
      };
      if ( !strcmp(inps[i],"-idRun") ) {
	if ( numinp-1 < i+1 ) {
	  r2d2usage();
	  exit(-3);
	};
	char *pEnd;	
	run = strtoull(inps[i+1],&pEnd,0);	
      };
      if ( !strcmp(inps[i],"-filename") ) {
	if ( numinp-1 < i+1 ){
	  r2d2usage();
	  exit(-3);
	};
	filename = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-host") ) {
	if ( numinp-1 < i+1 ){
	  r2d2usage();
	  exit(-3);
	};
	host = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-user") ) {
	if ( numinp-1 < i+1 ){
	  r2d2usage();
	  exit(-3);
	};
	user = (TString)inps[i+1];	
      };
      if ( !strcmp(inps[i],"-psw") ) {
	if ( numinp-1 < i+1 ){
	  r2d2usage();
	  exit(-3);
	};
	psw = (TString)inps[i+1];	
      };
      i++;
    };
    //
  } else {
    //
    // no input parameters exit with error, we need at least the run id.
    //
    r2d2usage();
    exit(-2);
  };
  //
  // Connect to the DB
  //
  dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
  if( !dbc ) throw -2;    
  //
  bool connect = dbc->IsConnected();
  //
  if( !connect ){
    printf(" Error, not connected to DB\n");
    exit(-1);
  };    
  //
  GL_ROOT *glroot = new GL_ROOT();
  GL_RUN *glrun = new GL_RUN();
  //
  if ( run != 0ULL ){
    error = glrun->Query_GL_RUN(run,dbc);
    error = glroot->Query_GL_ROOT(glrun->ID_REG_RUN,dbc);
    if ( error ){
      printf(" Error querying the DB! \n");
      exit(-4);
    };
    printf("\n Run %llu belongs to file %s \n",run,(glroot->PATH+glroot->NAME).Data());
  };
  if ( strcmp(filename.Data(),"") ){
    TSQLResult *pResult;
    TSQLRow *Row;
    int t;
    int r;
    stringstream myquery;
    // ----------------
    Int_t ID = 0;
    Int_t ID_RAW = 0;
    //    
    const char *rawpath = "";
    const char *rawname = "";
    //
    myquery.str("");
    myquery << "select ";
    myquery << " ID"; 
    myquery << ",ID_RAW"; 
    myquery << ",PATH"; 
    myquery << ",NAME"; 
    myquery << " from GL_ROOT where NAME=\"" << filename.Data() << "\";";    
    pResult = dbc->Query(myquery.str().c_str());
    if(!pResult->GetRowCount()) return (-51); 
    for( r=0; r < 1000; r++){ 
      Row = pResult->Next();      
      if( Row == NULL ) break;
      for( t = 0; t < pResult->GetFieldCount(); t++){ 
	if(t==0) ID     = atoi(Row->GetField(t));
	if(t==1) ID_RAW = atoi(Row->GetField(t));
      };
    };
    delete pResult;   
    printf("\n File %s contains the following runs: \n",filename.Data());
    myquery.str("");
    myquery << "select ";
    myquery << " ID"; 
    myquery << " from GL_RUN where ID_REG_RUN=" << ID << ";";    
    pResult = dbc->Query(myquery.str().c_str());
    if(!pResult->GetRowCount()) return (-51); 
    for( r=0; r < 1000; r++){ 
      Row = pResult->Next();      
      if( Row == NULL ) break;
      for( t = 0; t < pResult->GetFieldCount(); t++){ 
	if (t==0) printf(" => %i \n",atoi(Row->GetField(t)));
      };
    };
    delete pResult;   
    myquery.str("");
    myquery << "select ";
    myquery << " PATH,NAME"; 
    myquery << " from GL_RAW where ID=" << ID_RAW << ";";    
    pResult = dbc->Query(myquery.str().c_str());
    if(!pResult->GetRowCount()) return (-51); 
    for( r=0; r < 1000; r++){ 
      Row = pResult->Next();      
      if( Row == NULL ) break;
      for( t = 0; t < pResult->GetFieldCount(); t++){ 
	if(t==0) rawpath = Row->GetField(t);
	if(t==1) rawname = Row->GetField(t);
      };
    };
    delete pResult;   
    printf(" and belongs to raw data file %s/%s \n",rawpath,rawname);
  };  
  //
  // Close the DB connection
  //
  if ( dbc ) dbc->Close();
  //
  printf("\n");
  //
  exit(0);
}
