#!/usr/bin/env python3

#This script will produce the same output as the C++ app_testread, but it will not carry out as many tests behind the scenes.

import GriffDataRead
import Core.FindData
import Core.FPE
import sys

Core.FPE.catch_fpe()
datafile = Core.FindData("GriffDataRead","10evts_singleneutron_on_b10_full.griff")
dr = GriffDataRead.GriffDataReader(datafile,3)

print("Now dumping all data in selected events:\n")
dr.goToFirstEvent()
ievt = 0

#fixme, figure out how to make python __cmp__ operators use the .transient_id()!!
material_ids_seen = set()
materials=[]
while dr.eventActive():
    print("(ievt,seed,run,evt,mode)=(%i,%i,%i,%i,%s): ntrks=%i"%(ievt,dr.seed(),dr.runNumber(),dr.eventNumber(),dr.eventStorageMode(),dr.nTracks()))
    for trk in dr.tracks:
        print("   +", end='',flush=True)
        trk.dump_full()
        print()
        for seg in trk.segments:
            print("      + segment%i="%seg.iSegment(), end='',flush=True)
            seg.dump()
            print()
            for imat in range(seg.volumeDepthStored()):
                mat=seg.material(imat)
                if not mat.transient_id() in material_ids_seen:
                    material_ids_seen.add(mat.transient_id())
                    materials+=[mat]
            stepmax = seg.nStepsStored()
            for step in seg.steps:
                #reduce the size of the test logfile a bit by not printing each and every step:
                if step.iStep()<4 or step.iStep()>stepmax-3 or step.iStep()%20==0:
                    print("         + step%i="%step.iStep(), end='',flush=True)
                    step.dump()
                    print()
    if ievt>10 and ievt<27:
        ievt+=4
        dr.skipEvents(4)
    else:
        ievt+=1
        dr.goToNextEvent()


print("Found %i different materials:"%len(materials))
for mat in materials:
    print("    +", end='',flush=True)
    mat.dump()
    print()
    for elem in mat.elements:
        print("       +", end='',flush=True)
        elem.dump()
        print()
        for iso in elem.isotopes:
            print("          +", end='',flush=True)
            iso.dump()
            print()

print("ievt=%i"%ievt)
if ievt!=30:
    print("Error: Did not find 3*10 events when running through the file 3 times!")
    sys.exit(1)

if False:
    #Test default loop arg:
    dr=GriffDataRead.GriffDataReader(datafile)
    #Test list arg:
    dr=GriffDataRead.GriffDataReader([datafile,datafile,datafile])#todo: make this work!
