#include <G4Material.hh>
#include <G4VisAttributes.hh>

#include <RAT/PMTConstructorParams.hh>
#include <RAT/Materials.hh>
#include <RAT/Surfaces.hh>
#include <RAT/Log.hh>
using namespace RAT;

#include <string>
using namespace std;

PMTConstructorParams::PMTConstructorParams( const std::string& pmtType,
                                            G4VisAttributes* visAttributes )
{
  fPMTType = pmtType;
  Construct();
  fVisAttributes = new G4VisAttributes( *visAttributes );
}

void
PMTConstructorParams::Construct()
{
  DBLinkPtr pmtTable = DB::Get()->GetLink( "PMT", fPMTType );

  switch( pmtTable->GetI( "model_shape" ) )
    {
    case 0: // Torus
      fShape = eTorus;
      fEdgeZCoord = pmtTable->GetDArray( "z_edge" );
      fEdgeRhoCoord = pmtTable->GetDArray( "rho_edge" );
      fOriginZCoord = pmtTable->GetDArray( "z_origin" );
      break;
    case 1: // Cuboid
      fShape = eCuboid;
      fXWidth = pmtTable->GetD( "x_width" );
      fYWidth = pmtTable->GetD( "y_width" );
      fHeight = pmtTable->GetD( "height" );
      break;
    case 2: // Cylindrical
      fShape = eCylindrical;
      fHeight = pmtTable->GetD( "height" );
      fRadius = pmtTable->GetD( "radius" );
      break;
    }
  fModelType = pmtTable->GetS( "model_type" );
  fModelParams = pmtTable->GetS( "model_params" );
  fGlassThickness = pmtTable->GetD( "wall_thickness" );
  fDynodeRadius = pmtTable->GetD( "dynode_radius" );
  fDynodeTopZCoord = pmtTable->GetD( "dynode_top" );
  fPCMirrorOverlapTop = pmtTable->GetD( "photocathode_mirror_overlap_top" );
  fPCMirrorOverlapBottom  = pmtTable->GetD( "photocathode_mirror_overlap_bottom" );
  fGlassMaterial = G4Material::GetMaterial( pmtTable->GetS( "glass_material" ) );
  fVacuumMaterial = G4Material::GetMaterial( pmtTable->GetS( "pmt_vacuum_material" ) );
  fDynodeMaterial = G4Material::GetMaterial( pmtTable->GetS( "dynode_material" ) );
  fPhotocathodeSurface = Surfaces::GetSurface( pmtTable->GetS( "photocathode_surface" ) );
  fMirrorSurface = Surfaces::GetSurface( pmtTable->GetS( "mirror_surface" ) );

  //Some Error Checking
  if( fPhotocathodeSurface == 0 )
    Log::Die( "GeoPMTBuilderBase::ConstructPMT error: photocathode surface \"" + pmtTable->GetS( "photocathode_surface" ) + "\" not found" );
  if( fMirrorSurface == 0 )
    Log::Die( "GeoPMTBuilderBase::ConstructPMT error: mirror surface \"" + pmtTable->GetS( "mirror_surface" ) + "\" not found" );
}