from __future__ import print_function
import numpy as np 

from putIntoFigures_Utils import *

MAIN_PATH = "/home/renata/Documents/LHCb/Dizertacka/"
decName = "KplusPi0Resolved"

angles = ["ctk", "ctl", "phi"]
params  = ["Fl",
        "S3",
        "S4",
        "S5",
        "Afb",
        "S7",
        "S8",
        "S9",
        "m_b",
        "m_sigma_1",
        "alpha_1",
        "alpha_2",
        "n_1",
        "n_2"
]

#==============================================================#
#   Get all pics in the folder and put them in a latex figure  #
#==============================================================#

#Dumps all figures from the file into a list
def read_ls(path):
    import subprocess
    from subprocess import Popen, PIPE

    command = subprocess.Popen('ls '+path, shell=True, stdout=subprocess.PIPE)	
    stdout = command.communicate()[0] #gives the return of the ls, second member of the list is not important
    return stdout.decode().split('\n') #splits the string into a list of files that are in the folder    

# Put figs in one figure
def print_figures_from_ls_plus(path):
    for fig in read_ls(path):
        print("\\includegraphics[width=0.99\\textwidth]{%s}" % (fig))
    return    

#======================================================================#
#   Get all pics from a list with __LOOP__ and put them in one figure  #
#======================================================================#

def make_figure(folder, mainName, listOfEntries, figsPerRow, figType, outputFile):
    
    #Get width of the pic based on the number of plots per row
    picWidth = 0.9/figsPerRow    
    
    #Pass in the mainName of the figure with __LOOP__ where the loop should happen
    lineList = []
    for num,x in enumerate(listOfEntries,start =1):
        name = mainName.replace("__LOOP__",x,1)
        newLine = "\\\\" if (num%figsPerRow==0) else "" #Put // at the end of each row
        lineList.append("\t\\includegraphics[width=" + "%.2f" %picWidth  +"\\textwidth]{" + folder + name + figType + "}"+newLine)

    #Open the file
    f = open(MAIN_PATH+outputFile+".tex",'w')
    print("\\begin{figure}[hbt!]",file = f) 
    print("\\centering",file = f)
    for line in lineList:
        print(line, file =f) #Print the includegraphics
    print("\\captionof{figure}[]{\label{}}",file = f)
    print("\\end{figure}",file = f)
    f.close()

    print("\\include{"+outputFile+"}")
    return

def fig_angCorr_proj(angle, Run):
    listOfEntries = list(map(str,np.arange(0,18,1))) #Create a list of "1", "2", "3", ...
    make_figure(folder = "./Angular/projections/",
                mainName = angle+"eff__LOOP___"+decName+"_Run"+str(Run),
                listOfEntries = listOfEntries,
                figsPerRow=3, figType = ".eps",
                outputFile = "Chapters/Acceptance/app_angProj" + angle+"_Run"+str(Run)
            )
    return

for angle in angles:
    fig_angCorr_proj(angle, 1)
    fig_angCorr_proj(angle, 2)
