#include <iostream>
#include <TString.h>
#include "PamVMCSQLMgr.h"


using std::cout;
using std::endl;

PamVMCSQLMgr * PamVMCSQLMgr::fsql = 0;

PamVMCSQLMgr * PamVMCSQLMgr::Instance(){

  if(fsql == 0) {
    fsql = new PamVMCSQLMgr();
  }
  return fsql;
}
 
PamVMCSQLMgr::PamVMCSQLMgr(){
 
  TString G4WORKDIR=gSystem->Getenv("G4WORKDIR");
  TString PLATFORM=gSystem->Getenv("PLATFORM");
  
  fpathtodata = G4WORKDIR+"/lib/tgt_"+PLATFORM;
  fdbhost = gSystem->Getenv("PAM_DBHOST");
  fdbuser = gSystem->Getenv("PAM_DBUSER");
  fdbpsw = gSystem->Getenv("PAM_DBPSW");
  fdbc = TSQLServer::Connect(fdbhost.Data(),fdbuser.Data(),fdbpsw.Data());
  fglt = new GL_TABLES(fdbhost.Data(),fdbuser.Data(),fdbpsw.Data());
  fglparam = new GL_PARAM();
  fglroot = new GL_ROOT();
  fglcalo = new GL_CALO_CALIB();

  if(fdbc){
    //
    // Use UTC in the DB and make timeout bigger
    //
    stringstream myquery;
    myquery.str("");
    myquery << "SET time_zone='+0:00'";
    fdbc->Query(myquery.str().c_str());
    myquery.str("");
    myquery << "SET wait_timeout=173000;";
    fdbc->Query(myquery.str().c_str());
    //
  }

  if ( fglt->IsConnected(fdbc) ){
    cout<<"DB was connected.. Information:"<<endl
	<<"    SQL: "<<fdbc->GetDBMS()<<endl
	<<"VERSION: "<<fdbc->ServerInfo()<<endl
	<<"   HOST: "<<fdbc->GetHost()<<endl
	<<"   PORT: "<<fdbc->GetPort()<<endl;

  } else {
    cout<<"All paths to calibration files will be load from file"
	<<fpathtodata+"/calib_path.txt"<<endl;

    //Here I'll implement a possibility to load paths to detector
    //calibration files to use software in GRID (without DB)
    //in this case standard directory to keep all datafiles 
    //should be the library directory

  }
}
