import json
import glob
import math
from decimal import Decimal

from optparse import OptionParser
parser = OptionParser()
parser.add_option("--inputPaths", type="string", dest="inputPaths")
parser.add_option("--inputNames", type="string", dest="inputNames")
#parser.add_option("--listOfkeys", type="string", dest="listOfkeys")
parser.add_option("--noSig", action='store_true',dest="noSig", default=False)
parser.add_option("--loSig", action='store_true',dest="loSig", default=False)
parser.add_option("--last", action='store_true',dest="last", default=False)
parser.add_option("--unblind", action='store_true',dest="unblind", default=False)
(options, args) = parser.parse_args()
inputPaths = options.inputPaths.split(":")
inputNames = options.inputNames.split(":")
noSig=options.noSig
loSig=options.loSig
last = options.last
unblind = options.unblind
def numberconverter(ns,nround=2):
    if float(ns) > 0.01:
        if nround is 2:
            return "{:.2f}".format(round(float(ns),nround))
        if nround is 1:
            return "{:.1f}".format(round(float(ns),nround))
        if nround is 1:
            return "{:.0f}".format(round(float(ns),nround))
        return str(round(float(ns),nround))
    else:
        #return str("{:.2E}".format(Decimal(ns)).replace('0.00E+2','-').replace())
        return('-')


jsonsRun2 = []
for p in inputPaths:
    with open(p) as tempfile:
        jsonsRun2.append(json.loads(json.load(tempfile)))

#listOfkeys = options.listOfkeys.split(':')
#listOfkeys=[]
#for d in jsonsRun2:
#    for k in d.keys():
#        if k not in listOfkeys:
#            if "data_obs" not in k and 'total' not in k and 'qqHH' not in k and 'ggHH' not in k and 'signal' not in k and 'Total' not in k:
#                listOfkeys.append(k)
#listOfkeys=['ZZ',"WZ","Convs",'data_fakes',"Flips","singleH","Other"] 
listOfkeys=['ZZ',"WZ","Convs",'data_fakes',"Flips","singleH","Other",'DY','TTX','W','TT'] 
for k in jsonsRun2[0].keys():
    if k not in listOfkeys:
        if 'signal' not in k and 'qqHH' not in k and 'ggHH' not in k:
            print k

print"\\begin{center}"
print"\\begin{scriptsize}"
if len(inputNames) is 1:
    print '\\begin{tabular}{lr@{ $\pm$ }l}'
if len(inputNames) is 2:
    print '\\begin{tabular}{lr@{ $\pm$ }lr@{ $\pm$ }l}'
if len(inputNames) is 3:
    print '\\begin{tabular}{lr@{ $\pm$ }lr@{ $\pm$ }lr@{ $\pm$ }l}'
if len(inputNames) is 4:
    print '\\begin{tabular}{lr@{ $\pm$ }lr@{ $\pm$ }lr@{ $\pm$ }lr@{ $\pm$ }l}'
if len(inputNames) is 5:
    print '\\begin{tabular}{lr@{ $\pm$ }lr@{ $\pm$ }lr@{ $\pm$ }lr@{ $\pm$ }lr@{ $\pm$ }l}'
print '\\hline'
firstline = 'Process '
for n in inputNames:
    nalt = n
    if "3l1tau" in n:
        nalt='\lllt'
    elif "3l" in n:
        nalt = "\lllnot"
    if "2l2tau" in n:
        nalt= '\lltt'
    if "4l" in n:
        nalt = '\llll'
    if "2lss" in n:
        nalt='\llss'
    if "0l4tau" in n:
        nalt = '\\noltttt'
    if "1l3tau" in n:
        nalt= '\lttt'
    if "WZCR" in n:
        nalt= '\\threeLeptonCR'
    if "ZZCR" in n:
        nalt= '\\fourLeptonCR'
    firstline = firstline + '&' + '\multicolumn{2}{c}{' + nalt +'}' 
firstline = firstline + "\\\\" 
print firstline
print '\\hline'
nround = 2
if not noSig:
    secondline = 'SM $\\ggHH\\rightarrow\WWWW$ ($\\times\,30$)'
    thirdline = 'SM $\\ggHH\\rightarrow\WWtt$  ($\\times\,30$$)'
    fourthline = 'SM $\\ggHH\\rightarrow\\tttt$  ($\\times\,30$)'
    if not loSig:
        secondline = 'SM $\\HH\\rightarrow\VVVV$  ($\\times\,30$)'
        thirdline = 'SM $\\HH\\rightarrow\VVtt$  ($\\times\,30$)'
        fourthline = 'SM $\\HH\\rightarrow\\tttt$  ($\\times\,30$)'
    for n, name in enumerate(inputNames):
        if ("3l" in name or "2lss" in name or "CR" in name) and "3l1tau" not in name: 
            nround = 0
        else:
            nround = 1
        if 'signal_4vscaled' in jsonsRun2[n].keys():
            secondline = secondline+ '&' + numberconverter(jsonsRun2[n]['signal_4vscaled'][0],nround) + '&$' + numberconverter(jsonsRun2[n]['signal_4vscaled'][1],nround)+ '$'
        else:
            secondline = secondline+ '& \multicolumn{2}{c}{---} & \multicolumn{2}{c}{---}'
        if 'signal_2v2tscaled' in jsonsRun2[n].keys():
            thirdline = thirdline+ '&' + numberconverter(jsonsRun2[n]['signal_2v2tscaled'][0],nround) + '&$' + numberconverter(jsonsRun2[n]['signal_2v2tscaled'][1],nround) 
        else:
            thirdline = thirdline+ '& \multicolumn{2}{c}{---} & \multicolumn{2}{c}{---}'
        if 'signal_4tscaled' in jsonsRun2[n].keys():
            fourthline = fourthline+ '&' + numberconverter(jsonsRun2[n]['signal_4tscaled'][0],nround) + '&$' + numberconverter(jsonsRun2[n]['signal_4tscaled'][1],nround) + '$'
        else:
            fourthline = fourthline+ '& \multicolumn{2}{c}{---} & \multicolumn{2}{c}{---}'
    secondline = secondline + "\\\\" 
    thirdline = thirdline + "\\\\" 
    fourthline = fourthline + "\\\\" 
    print secondline
    print thirdline
    print fourthline
    print " \\\\"

for key in listOfkeys:
    name = key
    if "Other" in name: name = "Other backgrounds"
    #if "singleH" in name: name = "ggH + qqH + ttH + tH + VH"
    if "singleH" in name: name = "Single Higgs"
    if "data_fakes" in name: name = "Fakes"
    if "Flips" in name: name = "Flips background"
    if "Convs" in name: name = "Conversion"
    if "ZZ" in name: name= '$\PZ\PZ$'
    if "WZ" in name: name= '$\PW\PZ$'
    #if "TTX" in name: name = "$t\\bar{t}$ + X"
    #elif "TT" in name: name = "$t\\bar{t}$"
    line = name
    for n, name in enumerate(inputNames):
        if ("3l" in name or "2lss" in name or "CR" in name) and "3l1tau" not in name: 
            nround = 0
        else:
            nround = 1
        if key in jsonsRun2[n].keys():
            line = line + '&' + numberconverter(jsonsRun2[n][key][0],nround) + '&$' + numberconverter(jsonsRun2[n][key][1],nround) + '$'
        else: 
            line = line +'& \multicolumn{2}{c}{---} & \multicolumn{2}{c}{---}'
    line = line + "\\\\"
    print line
bgline = 'Total expected background   '
for n, name in enumerate(inputNames):
    if ("3l" in name or "2lss" in name or "CR" in name) and "3l1tau" not in name: 
        nround = 0
    else:
        nround = 1
    bgline = bgline+ '&' + numberconverter(jsonsRun2[n]['totalBG'][0],nround) + '&$' + numberconverter(jsonsRun2[n]['totalBG'][1],nround) + '$'
bgline = bgline + "\\\\"
print bgline
print " \\\\"
dataline = 'Data'
for n, name in enumerate(inputNames):
    if 'data_obs' in jsonsRun2[n].keys():
        dataline = dataline+ '&' + '\multicolumn{2}{c}{'+str(int(float(jsonsRun2[n]['data_obs'][0])))+'}'
    else: dataline = dataline+ '& \multicolumn{2}{c}{---} & \multicolumn{2}{c}{---}'
dataline = dataline +  " \\\\"
print dataline
print '\\hline'
print '\\end{tabular}'
if last:
    print '\\begin{tabular}{l}'
    if loSig:
        print "%$\dagger$ The $\HH$ signal represents the sum of the \ggHH and \qqHH production processes and is normalized to $30 times$ the event yield expected in the SM \\\\"
        print "$\dagger$ The $\HH$ signal represents the LO \ggHH production processes normalized a $\HH$ cross section of 1pb with SM kinematics."
    else:
        print "$\dagger$ The $\HH$ signal represents the sum of the \ggHH and \qqHH production processes and is normalized to $30 times$ the event yield expected in the SM\\\\"
    print '\\end{tabular}'
print"\\end{scriptsize}"
print"\\end{center}"
