##
# @author    Nikos Karastathis < nkarast .at. cern .dot. ch >
#
# @brief     Macro to make the SF validation plots and generate the tex
#
import os
import sys
import time 
from array import array
import ROOT as rt
from optparse import OptionParser
from logging import *

#!! --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*
##	Prints out the help menu of main
#	Inputs:  [None]
#	Returns: [None]
def usage():
	c="""
Options:
--sf-file 		: the SF file [if not given, main exits]

--point, -p		: specify selection/isolation point [can be csv]

--trigger		: specify trigger [can be csv]

--period 		: specify period [can be csv]

--outdir, -o 	: specify output directory [if not given 
					plots-sf-DD-MM-YYYY will be created]

--tex, -t 		: if given a tex will be generated	

--do-plot-iso 	: [flag - default: False] adds the isolation points

--do-fine 		: [flag - default: False] do fine binning eta-phi

--do-syst 		: [flag - default: False] do also MC systematic variations

--do-png  		: [flag - default: False] save canvas as png

--do-all 		: [flag - default: False] do all selections/isolation points, 
											all triggers, all variations

--debug, -d 	: [flag - default: False] logger prints out everything above 
											debug (default: info)				

--do-compile, -c: [flag - default: False] compile generated TeX with pdflated

--do-clean		: [flag - default: False] after TeX compilation clean up 
											intermediate files

--do-tex-only	: [flag - default: False] Don't make plots, only TeX

--help, -h		: [flag - default: False] Print help


Returns: [None]"""
	print(c)


#!! --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*
##	Get the efficiency latex to be drawn on plot
#	Inputs: - x 	= x position
#			- text 	= the text string
#			- color	= the color of text (default black)
#	Returns: - TLatex object
def getEffLatex(x, text, color=1):

    xlep = rt.TLatex(x, 0.93, text)
    xlep.SetNDC()
    xlep.SetTextFont(42)
    xlep.SetTextSize(0.045)
    xlep.SetTextAlign(12)
    xlep.SetTextColor(color)
    xlep.Draw()

    return xlep

#!! --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*
##	Returns a string with the date in DD-MM-YYYY , separator can be set
#	Inputs: sep -> the separator in date, [default : - ]
#	Returns: date string
def getDate(sep="-"):
	return time.strftime("%d"+sep+"%m"+sep+"%Y")

#!! --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*
##	Check if a file exists, else raise SystemExit
#	Inputs: - infile 	=  the filename
#	Returns: [None]
def checkFile(infile):
	if os.path.isfile(infile): 
		info("Opening file %s... OK" % infile)
	else:
		fatal("File does not exist! Terminating...")
		raise SystemExit(0)

#!! --*--*--*--*--*--*--
*--*--*--*--*--*--*--*--*--*--*--*
##	Set the gStyle 
#	Inputs:  [None]
#	Returns: [None]
def setStyle():
	rt.gStyle.SetOptStat(0)
	rt.gStyle.SetPadTopMargin(0.10)
	rt.gStyle.SetPadBottomMargin(0.15)
	rt.gStyle.SetPadLeftMargin(0.15)
	rt.gStyle.SetPadRightMargin(0.20)
	rt.gStyle.SetPaintTextFormat('
0.2f')
	rt.gStyle.SetPalette(1)
	rt.gROOT.ForceStyle()

#!! --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*
##	Checks if a directory exists, if not it can create it
#	Inputs:  directory  = the directory to check
#			 create [bool] = Create the directory if it does not exist
#	Returns: True  -> Directory already exists
#			 False -> Directory did not exist and maybe (if create=True) now it does
def checkDir(directory, create=True):
    if not os.path.exists(directory):
        if create: os.makedirs(directory)
        return False
	return True


#!! --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*
##	Draws a histogram and saves the canvas in pdf format (or png if png==True)
#	Inputs:	hist		-> The histogram to be drawn
#			point		-> The isolation point - used for savename and TLatex
#			trigger		-> The trigger - used for savename and TLatex
#			region		-> The detector region - used for savename, TLatex and draw option
#			sample		-> "Data", "MC" or "Data/MC" [is lower() and replace("/","_")]
#			variable	-> The variable to be plotted [placeholder for more?]
#			variation	-> "Nominal", "stat/syst_up/down", or "[variation]_over_Nominal"
#			outdir		-> Output directory
#			png	[Bool]	-> If true save canvas as png else pdf (default)
#	Returns: [None]
def drawHist(hist, point, trigger, region, sample, variable, variation, outdir, png=False):
	## the sample and variations transformed to lower case, and "/" are removed from the sample
	canvas_id = "plot_prepTP_"+point+"_"+region+"_Match_"+trigger+"_probe_"+region+"_"+variable+"_"+sample.lower().replace("/","_")+"_"+variation.lower()
	canvas = rt.TCanvas(canvas_id,canvas_id, 750, 600)
	canvas.cd()
	setStyle()
	draw_opt = 'COLZ TEXT'
	if 'endcap' in region:
		draw_opt = 'COLZ TEXT90' ## pretty!

	##	check if the current variations is the ratio of [variation]_over_Nominal and 
	#	split the string using the _over_ 
	if("over" in variation):
		ztitle = sample+" "+variation.lower().split("_over_")[0]+" / "+variation.lower().split("_over_")[1]
	else:
		ztitle = sample+" "+variation

	hist.GetZaxis().SetTitle(ztitle)
	hist.GetZaxis().SetTitleOffset(1.25)
	hist.GetZaxis().SetRangeUser(0.3, 1.1)
	hist.GetZaxis().CenterTitle()
	hist.Draw(draw_opt)

	## get the efficiency latex - to be drawn above histo border
	lpr = getEffLatex(0.10, '%s  %s/%s' %(region, trigger.replace('HLT_', ''), point))
	lpr.Draw()

	## check if the outdir exists, else create it
	dummy_bool = checkDir(outdir)

	## change the suffix pdf or png
	if(png): saveName = outdir +"/"+ canvas_id+".png"
	else: saveName = outdir +"/"+ canvas_id+".pdf"
	canvas.SaveAs(saveName)

#!! --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*
##	Generates a TeX file with the summary plots. If configured, the function also compiles it.
#	Inputs:	tex_name		-> the name of the TeX file to be generated
#			plot_folder		-> the folder containing the plots
#			slide_title		-> the title of the presentation
#			selections 		-> the list of selections/isolation points 
#			triggers		-> the list of triggers
#			regions 		-> the list of detector regions
#			png	[Bool]		-> If true the plots are in .png format, else .pdf (default : pdf)
#			compile	[Bool]	-> If true the TeX file is compiled into a pdf (default: False)
#			clean [Bool]	-> If true & compile true, only the .tex and .pdf files will remain 
#	Returns: [None]
def makeTex(tex_name, plot_folder, slide_title, selections, triggers, regions, png=False, compile=False, clean=True):

	### tex file name

	if ".tex" in tex_name :
		filename=tex_name
	else:
		filename=tex_name+".tex"

	fileout = open(filename, "w")

	if(png): suffix=".png"
	else: suffix=".pdf"

	variables = [ 
				['Efficiency' , ['data_nominal', 'mc_nominal', 'data_mc_nominal']],
				['Uncertainties' , ['data_stat_down_over_nominal', 'data_stat_up_over_nominal' , 
									'mc_syst_down_over_nominal', 'mc_syst_up_over_nominal']]
				]


	def a(str):
		fileout.write(str+"\n")
	
	a("\documentclass[aspectratio=169,hyperref={pdfpagelayout=SinglePage}]{beamer}")
	a("\usetheme{default}")
	a("\usepackage{graphicx}")
	a("\usepackage{xspace}")
	a("\usepackage{amsmath}")
	a("\usepackage{multicol}")
	a("\\begin{document}")
	a("\\title["+slide_title+"]{"+slide_title+"}")
	a("\\author{Muon Trigger Signature Group}")
	a("\\date{\\today}")
	a("\\begin{frame}")
	a("\\titlepage")
	a("\end{frame}")
	a("\\begin{frame}[allowframebreaks]")
	a("\\frametitle{Table of Contents [Clickable]}")
	a("\\tiny{")
	a("\\begin{multicols}{2}")
	a("\\tableofcontents")
	a("\end{multicols}")
	a("}") #//small
	a("\end{frame}")

	for selection in selections:
		a(" ")
		rpl_sel = selection.replace("_","\_")
		a("\\section{"+rpl_sel+"}")
		a("\\begin{frame}")
		a("\\begin{center}")
		a("\\Large{\\textbf{"+rpl_sel+"}}\\\\")
		a("\\end{center}")
		a("\\end{frame}")
		


		for trigger in triggers:
			a(" ")
			rpl_trig = trigger.replace("_","\_")
			a("\\subsection{"+rpl_trig+"}")
			a("\\begin{frame}")
			a("\\begin{center}")
			a("\\Large{\\textbf{"+rpl_trig+"}}\\\\")
			a("\\end{center}")
			a("\\end{frame}")
			


			for region in regions:
				for ivar in variables:
					a("\\begin{frame}")
					a("\\frametitle{\small{