#!/home/moi/ProtoMemoires/venv/bin/python
import glob,subprocess
#-------------------------------------------            
def addpath(x,ajout):
    # Pour transformer les chemins vers les images
    #if "includegraphics" in x:
    if "input" in x:
        return x.replace("{",ajout)
    else:
        return x
#
# Récupérer la liste des textes à introduire
#
path2add="../Sources/Courante"
with open("all_texts") as f:
    lf0=  f.readlines()
    lf=[]
    for x in lf0:
        if len(x)!= 0 and x[0]!= "#":
            xs=x.split()
            if len(xs) ==1:
                lf.append((xs[0],))
            else:
                lf.append((xs[0],xs[1]))

# faire la liste des *.bib (éventuels):
forbiblatex={}
for f in lf:
    forbiblatex[f]=",".join([x for x
                             in glob.glob(f"{path2add}/{f[0].split("/")[0]}/*.bib")])
allbibfiles=[forbiblatex[k] for k in forbiblatex.keys()  if forbiblatex[k]!=""]

print("\nFichiers bib",allbibfiles,"\n")

#
# Récuperer le template
#
templat= "../tpl.tex"
#
with open(templat) as f:
    Ltmpl=f.readlines()

#
# ne garder du template que le début
# en ajoutant les ressouces pour biblatex
#
Lall=[]
for l in Ltmpl:
    if "%@@debut" in l:
        break
    else:
        if "addbibresource" in l:
            # ajouter les chemins vers les fichiers bib
            # 
            for x in allbibfiles:
                Lall.append(f"\\addbibresource{{{x}}}\n")
            T=[f'{{{path2add}/{x[0].split("/")[0]}}}' for x in lf]
            T=f"\\graphicspath{{ {''.join(T)} }}\n"
            Lall.append(T)
        Lall.append(l)

#
# parcourir les fichiers à assembler:
#
for l in lf:
    do_eject= len(l) == 1 or (len(l)>1 and not "noeject" in l[1])
    do_vfill= len(l) == 1 or (len(l)>1 and not "novfill" in l[1])
    lok=f"{path2add}/"+l[0].replace("\n","")
    print("On traite :",lok)
    
    with open(lok) as g:
        LL=g.readlines()
    
    # insérer ce qui entre %@@debut et "%@@fin":
    start= False
    Z= []
    for x in LL:
        if "@@debut" in x:
            start= True
            print("--> start")
        
        if start:
            Z.append(x)
            if "@@fin" in x:
                break
            
    print("--> nl:",len(Z))
    # graphiques: modifier les chemins:
    #ajout="{../"+l[0].split("/")[0]+"/"
    ajout=f"{{{path2add}/{l[0].split("/")[0]}/"
    Lall+=[addpath(x,ajout) for x in Z if not "newcounter" in x]
    
    if do_vfill:
        #Lall.append("\\vfill\n")
        pass
    if do_eject:
        #Lall.append("\\eject\n")
        Lall.append("\\newpage\n")
    print("<-- ok\n")
#
# sauver le resultat....
with open("final.tex","w") as f:
    for x in Lall[:-1]:
        f.write(x)
    f.write("\\newpage\n")
    f.write("\\thispagestyle{empty}\n")
    f.write("\\fancyhead{}\n")
    f.write("\\input{refauteur.tex}\n")
    f.write("\\tableofcontents\n")
    f.write("\\end{document}\n")


print("Nombre d'entrées par auteur :")
with open("../genauteur.py") as f:
    exec(f.read())
print("-fin-\n")
