import sys
import pyastro
from gxml.parser import Parser

pyastro.get(verbose=False)
g = pyastro.gdict

if len(sys.argv):
   file = sys.argv[1]
else:
   file = "ObsProject.xml"
fp = open(file,"r")
p = Parser(fp)

#
# Fetch schemaVersion that supposedly contains something
tree = ["prj:ObsProject"]
(laddress,lmeta,ldata) = p.do(tree)
schemaversion=[str(toto['schemaVersion']) for toto in lmeta]
g.project.schemaversion=[str(toto['schemaVersion']) for toto in lmeta]
if schemaversion[0]=='12':
  print("This is a Cycle 0 project. Processing accordingly ")
  #
  # Fetch ScienceGoal naame
  tree = ["prj:ObsProject","prj:ObsProgram","prj:ScienceGoal","prj:name"]
  (laddress,lmeta,ldata) = p.do(tree)
  g.project.science_goal=[str(toto) for toto in ldata]
  #
  # Fetch ObsUnitSetRef entityId
  tree = ["prj:ObsProject","prj:ObsProgram","prj:ObsPlan","prj:ObsUnitSet","prj:SchedBlockRef"]
  (laddress,lmeta,ldata) = p.do(tree)
  g.project.obs_unit_set=[str(toto['entityId']) for toto in lmeta]
else:
  print("Schema version 13. Processing accordingly ")
  #
  # Fetch ScienceGoal naame
  tree = ["prj:ObsProject","prj:ObsProgram","prj:ObsPlan","prj:ObsUnitSet","prj:name"]
  (laddress,lmeta,ldata) = p.do(tree)
  g.project.science_goal=[str(toto) for toto in ldata]
  #
  # Fetch ObsUnitSetRef entityId
  # CYCLE 0 tree = ["prj:ObsProject","prj:ObsProgram","prj:ObsPlan","prj:ObsUnitSet","prj:SchedBlockRef"]
  tree = ["prj:ObsProject","prj:ObsProgram","prj:ObsPlan","prj:ObsUnitSet","prj:ObsUnitSet","prj:ObsUnitSet","prj:SchedBlockRef"]
  (laddress,lmeta,ldata) = p.do(tree)
  g.project.obs_unit_set=[str(toto['entityId']) for toto in lmeta]

fp.close()
