import ROOT
from ShipGeoConfig import ConfigRegistry
import shipDet_conf
from StrawHits import StrawHits


fileName = "ship.10.0.Pythia8-TGeant4_rec.root"
geoFile  = fileName.replace('ship.','geofile_full.').replace('_rec.','.')
f = ROOT.TFile(fileName)
t = f.Get("cbmsim")

dy = 10.

ShipGeo = ConfigRegistry.loadpy("$FAIRSHIP/geometry/geometry_config.py", Yheight = dy )
run     = ROOT.FairRunSim()
modules = shipDet_conf.configure(run,ShipGeo)
tgeom = ROOT.TGeoManager("Geometry", "Geane geometry")
gMan  = tgeom.Import(geoFile)
geoMat =  ROOT.genfit.TGeoMaterialInterface()
ROOT.genfit.MaterialEffects.getInstance().init(geoMat)
volDict = {}
i=0
for x in ROOT.gGeoManager.GetListOfVolumes():
  volDict[i]=x.GetName()
  i+=1

bfield = ROOT.genfit.BellField(ShipGeo.Bfield.max ,ShipGeo.Bfield.z,2, ShipGeo.Yheight/2.)
fM = ROOT.genfit.FieldManager.getInstance()
fM.init(bfield)


sh = StrawHits(t, modules, ShipGeo.straw.resol, 0)


for i in xrange(min([t.GetEntries(), 50])):
    t.GetEntry(i)
    
    if sh.readEvent()<2 : continue
  
    if sh.FitTracks()<2 : continue
        
    vertex3  = sh.getReFitVertex()
    doca     = sh.getDoca()
    for tid in sh.getReFitTrIDs():
      vPos3, vDir3, MomVal = sh.getReFitPosDirPval(tid)
      moment3              = vDir3*MomVal
      ndf                  = sh.getReFitNdf(tid)
      redChi2              = sh.getReFitChi2Ndf(tid)
      print "track MCid {0:4} ndf {1:8.2f} redChi2: {2:8.2f} momVal {3:8.2f} vector".format(tid, ndf, redChi2, MomVal),
      print "".join("{:8.2f}".format(moment3(ii)) for ii in range(0,3))
    print "\tvertex doca, v.x, v.y. v.z : {0:8.2f}".format(doca),
    print "".join("{:8.2f}".format(vertex3(ii)) for ii in range(0,3))