# -*- coding: utf-8 -*-
import os
import re
import random
import dircache
import sys

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ''

#===========================
# Input Variables
#===========================
print "Shall run Xml_Generate.py with these arguments of length",len(sys.argv)
print sys.argv

#i=0
#for token in sys.argv:
    #print i, token
    #i=i+1

Energy = sys.argv[1]

Particle = sys.argv[2]

ECALTOEM = sys.argv[3]
HCALTOEM = sys.argv[4]
ECALTOHAD = sys.argv[5]
HCALTOHAD = sys.argv[6]

CALIBR_ECAL_BARREL_INPUT = sys.argv[7]
CALIBR_ECAL_BARREL_INPUT2 = float(CALIBR_ECAL_BARREL_INPUT)

CALIBR_ECAL_BARREL = str(CALIBR_ECAL_BARREL_INPUT) + ' ' + str(CALIBR_ECAL_BARREL_INPUT2)
#Of the form: <parameter name="CalibrECAL" type="FloatVec">42.91 85.82 </parameter>

CALIBR_ECAL_ENDCAPCORR = sys.argv[8]

CALIBR_HCAL_BARREL = sys.argv[9]
CALIBR_HCAL_ENDCAP = sys.argv[10]
CALIBR_HCAL_OTHER = sys.argv[10]

MHHHE = sys.argv[12]

Slcio_Path = sys.argv[13]

Slcio_Format = sys.argv[14]

Gear_File_And_Path = sys.argv[15]

Pandora_Settings_File = sys.argv[16]

ECalGeVToMIP = sys.argv[17]
HCalGeVToMIP = sys.argv[18]
MuonGeVToMIP = sys.argv[19]

HCALBarrelTimeWindowMax = sys.argv[20]
HCALEndcapTimeWindowMax = sys.argv[21]
ECALBarrelTimeWindowMax = sys.argv[22]
ECALEndcapTimeWindowMax = sys.argv[23]
dd4hep_compactxml_File= sys.argv[24]

#===========================
Slcio_Format = re.sub('ENERGY',Energy,Slcio_Format)
Slcio_Format = re.sub('PARTICLE',Particle,Slcio_Format)

directory = os.getcwd()
job_name = Energy + '_GeV_Energy_' + Particle

ECAL_MIP_THRESHOLD = '0.5'
HCAL_MIP_THRESHOLD = '0.3'

baseFileName = 'CLIC_PfoAnalysis_AAAA_SN_BBBB.xml'

jobList = ''

Marlin_Path = os.getcwd() + '/../Marlin_Xml'

base = open(baseFileName,'r')
baseContent = base.read()
base.close()

baseFileName = re.sub('AAAA',job_name,baseFileName)

fileDirectory = Slcio_Path

allFilesInDirectory = dircache.listdir(fileDirectory)

inputFileExt = 'slcio'

allFiles = []
allFiles.extend(allFilesInDirectory)
allFiles[:] = [ item for item in allFiles if re.match('.*\.'+inputFileExt+'$',item.lower()) ]
allFiles.sort()


print "Found ",len(allFiles)," files."

##print allFiles

#print Slcio_Format
if allFiles:
    
    SN = 0
    
    array_size=len(allFiles)
    
    for nfiles in range (array_size):
      
        jobFiles = ''
        newContent = baseContent
        nextFile = allFiles.pop(0)
        matchObj = re.match(Slcio_Format, nextFile, re.M|re.I)
        
        #print nfiles, nextFile,matchObj

        if matchObj:
            SN = matchObj.group(1)
            
            #print SN
            newContent = re.sub('ECALTOEM_XXXX',ECALTOEM,newContent)
            newContent = re.sub('HCALTOEM_XXXX',HCALTOEM,newContent)
            newContent = re.sub('ECALTOHAD_XXXX',ECALTOHAD,newContent)
            newContent = re.sub('HCALTOHAD_XXXX',HCALTOHAD,newContent)
            newContent = re.sub('MHHHE_XXXX',MHHHE,newContent)
            newContent = re.sub('slcio_XXXX',Slcio_Path + nextFile,newContent)
            newContent = re.sub('Gear_XXXX',Gear_File_And_Path,newContent)
            newContent = re.sub('CALIBR_ECAL_BARREL_XXXX',CALIBR_ECAL_BARREL,newContent)
            newContent = re.sub('CALIBR_ECAL_ENDCAPCORR_XXXX',CALIBR_ECAL_ENDCAPCORR,newContent)            
            newContent = re.sub('CALIBR_HCAL_BARREL_XXXX',CALIBR_HCAL_BARREL,newContent)
            newContent = re.sub('CALIBR_HCAL_ENDCAP_XXXX',CALIBR_HCAL_ENDCAP,newContent)
            newContent = re.sub('CALIBR_HCAL_OTHER_XXXX',CALIBR_HCAL_OTHER,newContent)
            newContent = re.sub('EMT_XXXX',ECAL_MIP_THRESHOLD,newContent)
            newContent = re.sub('HMT_XXXX',HCAL_MIP_THRESHOLD,newContent)
            newContent = re.sub('ECalGeVToMIP_XXXX',ECalGeVToMIP,newContent)
            newContent = re.sub('HCalGeVToMIP_XXXX',HCalGeVToMIP,newContent)
            newContent = re.sub('MuonGeVToMIP_XXXX',MuonGeVToMIP,newContent)
            newContent = re.sub('HCALBarrelTimeWindowMax_XXXX',HCALBarrelTimeWindowMax,newContent)
            newContent = re.sub('HCALEndcapTimeWindowMax_XXXX',HCALEndcapTimeWindowMax,newContent)
            newContent = re.sub('ECALBarrelTimeWindowMax_XXXX',ECALBarrelTimeWindowMax,newContent)
            newContent = re.sub('ECALEndcapTimeWindowMax_XXXX',ECALEndcapTimeWindowMax,newContent)
            
            newContent = re.sub('PSF_XXXX',Pandora_Settings_File,newContent)
            newContent = re.sub('COMPACTXML_XXXX',dd4hep_compactxml_File,newContent)
            
            newContent = re.sub('pfoAnalysis_XXXX.root ', 'pfoAnalysis_' + job_name + '_SN_' + SN + '.root',newContent)
            
            newFileName = re.sub('BBBB',str(SN),baseFileName)
            
            Fullpath = os.path.join(Marlin_Path, newFileName)
            
            file = open(Fullpath,'w')
            file.write(newContent)
            file.close()
            
            jobList += Fullpath
            jobList += '\n'
            del jobFiles
            del newContent
            #print jobList
file = open( directory + '/../Root_File_Generation/Marlin_Runfile_' + job_name + '.txt','w')
file.write(jobList)
file.close()
#print '/../Root_File_Generation/Marlin_Runfile_' + job_name + '.txt'
