
#!/usr/bin/env python

import copy
import math
import os
import re
import sys
import logging
import string
import time

import ROOT

import PhysicsLight.PhysicsLightXSec    as XSec

import PhysicsMM.PhysicsMMInfo          as ttH

import plotCand_Utils as util

(options, args) = util.p.parse_args() 

log = Config.getLog(__name__, debug=options.debug)

#-------------------------------------------------------------------------
def makeCanvas(name):
    
    ROOT.gStyle.SetPadRightMargin (0.12) 
    can = ROOT.TCanvas(name, name, 900, 550)
    
    return can

#---------------------------------------------------------------------------------------------
def getDataHist(rfile, dfile, dpath):

    ohist=[]

    #
    # Some helper function which just get the list of strings according to histogram name
    #
    phists = util.getDataHistList(rfile, dfile, dpath)
   
    for hist in sorted(phists):
        
        if not  hist.count('NLepton'): continue
        if hist.count('Tight'): continue

        hpath = '%s/%s' %(dpath, hist)
        hname = hpath.replace('/', '_')
        
        #Another helper function in utilities to get the desried histogram
        hdata = util.getData(dfile, hpath)

        hdata.SetName('%s' %(hname))
        hdata.SetDirectory(0)
        
        ohist.append(hdata)

    return ohist

#-------------------------------------------------------------------------
def main():

    #
    # Check inputs
    #
    if len(args) < 1: 
        raise Exception('main - need at least one argument: %s' %(args))

    if len(args) == 1 and not os.path.isfile(args[0]):
        log.error('Invalid input file: %s' %args[0])
        sys.exit(1)

    timeStart = time.time()
    log.info('Current time: %s' %(time.asctime(time.localtime())))

    can = makeCanvas('can')    
     
    #
    # Open the root file
    #
    rfile = XSec.InputFileCollection(args)
    dfile = rfile

    #
    # Path of directory 
    #
    region_Test = ['CR_2l_4jets_1bjet',
                   ]

    #
    # Get the histogram
    #
    data_hist = getDataHist(rfile, dfile, region_Test[0])

    #
    # Plot the histogram
    #
    for i in data_hist:
        i.Sumw2()
        i.Draw('')
        can.cd()
        util.updateCanvas(can, name='%s'%i.GetName())
    
    log.info('Current time: %s' %(time.asctime(time.localtime())))
    log.info('Total job time: %.1fs' %(time.time()-timeStart))
#================================================================================
if __name__ == '__main__':
    main()
    log.info('All is done')

