from __future__ import print_function

import os.path
import glob
import sys
import time
import xml.etree.ElementTree as ET
import Manyo
import Manyo.MLF as mm
import Manyo.Utsusemi as mu
import Manyo.Emaki as me

if len(sys.argv) != 5:
    print("Usage: %s run_number wiring_info detector_info case_info"%sys.argv[0])
    print("Note:")
    print("")
    sys.exit()

ini_time = time.time()
Wfile = sys.argv[2]
Dfile = sys.argv[3]
RunNumber = int(sys.argv[1])
InstCode = 'ENG'
DataPath = '/data'
Cfile = sys.argv[4]
output_path = "%s%06d_trg.srlz"%(InstCode, RunNumber)

trig_file_template = os.path.join(DataPath, InstCode,\
                                  '{0}{1:06d}_????????'.format(InstCode, RunNumber),\
                                  '{0}{1:06d}_03_017_???.edb'.format(InstCode, RunNumber))
trig_files = glob.glob(trig_file_template)
print('TrigNET files')
print('----')
print(trig_files)
print('----')
T0DirTemplate = os.path.join(DataPath, InstCode,\
                                  '{0}{1:06d}_????????'.format(InstCode, RunNumber))
T0DirCandidates = glob.glob(T0DirTemplate)
T0DirCandidates.sort()
T0DataPath = T0DirCandidates[-1]
evt = me.EmakiEventDataConverterReadout1d()
evt.LoadParamFiles( Wfile, Dfile, Cfile )
evt.LoadTrignetEventFile(RunNumber, DataPath, T0DataPath)
evt.SetHistAllocation()
evt.LoadEventDataFiles(RunNumber, DataPath, T0DataPath)
case_xml = ET.parse(Cfile)
case_root = case_xml.getroot()
filters = case_root.find("filters")
num_filters = int(filters.get("n"))
print('Num. of filters: {0}'.format(num_filters))
for case_id in range(1,num_filters+1):
    print('Case ID: {0}.'.format(case_id))
    ecm = Manyo.ElementContainerMatrix()
    evt.SetElementContainerMatrix( ecm, case_id)
    si = Manyo.SearchInHeader(ecm)
    ecm_n = Manyo.ElementContainerMatrix()
    for i in range(5):
        for j in range(3):
            si.Search("PSDID", i*6+j)
            print("PSDID: {0}".format(i*6+j))
            eca = si.PutResultAsArray()
            ecm_n.Add(eca)
            del eca
    average = mm.AverageElementContainerMatrix(ecm_n)
    ec_av_n = average.GetAverage()
    del ecm_n, average
    out_av_n = "{0:s}{1:06d}_{2:04d}_n.srlz".format(InstCode, RunNumber, case_id)
    w = Manyo.WriteSerializationFileBinary(out_av_n)
    w.Save(ec_av_n)
    print("[o] Averaged histogram of north bank was serialized to {0}.".format(out_av_n))
    del w
    ecm_s = Manyo.ElementContainerMatrix()
    for i in range(5):
        for j in range(3):
            si.Search("PSDID", i*6+j+3)
            print("PSDID: {0}".format(i*6+j+3))
            eca = si.PutResultAsArray()
            ecm_s.Add(eca)
            del eca
    average = mm.AverageElementContainerMatrix(ecm_s)
    ec_av_s = average.GetAverage()
    del ecm_s, average
    out_av_s = "{0:s}{1:06d}_{2:04d}_s.srlz".format(InstCode, RunNumber,case_id)
    w = Manyo.WriteSerializationFileBinary(out_av_s)
    w.Save(ec_av_s)
    print("[o] Averaged histogram of south bank was serialized to {0}.".format(out_av_s))
    del w
    del ecm
print("Processed {0} sec.".format(time.time() - ini_time))
