import re, glob
import kutil
import font

def tex_style():
    result = ""
    for basename, filename in kutil.sks_files_of_type("sty"):
        with open(filename) as fp:
            src = fp.read()
        result += f"% {basename}.sty\n{src.strip()}\n\n"
    return result

# \usepackage{quoting}

def environment(name, body, required=None, optional=None):
    req = f"{{{required}}}" if required else ""
    opt = f"[{optional}]" if optional else ""
    result = f"""\\begin{{{name}}}{opt}{req}
{body}
\\end{{{name}}}
"""
    return result

def page(title, subtitle, leading, pointsize, ragged_right, body):
    title = f"\\textsf{{\\Large {title}}}" if title else ""
    subtitle = f"\\vspace*{{4pt}}\\textsf{{\\large {subtitle}}}" if subtitle else ""
    #leading = f"\\renewcommand{{\\baselinestretch}}{{{leading}}}"
    leading = f"\\setstretch{{{leading}}}"
    raggedright = "\\raggedright" if ragged_right else ""
    if title or subtitle:
        title = f"\\begin{{center}}{title} \\\\ {subtitle}\\end{{center}}\n\n"
    result = f"""\\documentclass[a4paper,{pointsize}]{{article}}
{tex_style()}
{leading}
{raggedright}
\\begin{{document}}
\\thispagestyle{{empty}}
"""
    result += title + body + "\n\\end{document}\n"
    return result

TARGET_ID = 0

#def add_caption(element, label, numbered, caption_text, center, side, width, side_center, vmargin, caption_margin):

def minipage(content, width="\\textwidth", vertical="c", center=True, vmargin="", outline=False):
    vertical = f"[{vertical}]" if vertical else ""
    center = "\n\\centering" if center else ""
    vmargin = f"\n\\vspace*{{{vmargin}}}" if vmargin else ""
    result = f"""\\begin{{minipage}}{vertical}{{{width}}}{center}{vmargin}
{content}{vmargin}
\\end{{minipage}}"""
    if outline:
        result = f"\\fbox{{{result}}}"
    return result

def caption_wrapper(element, hpos, bottom_margin=.67):
    vmargin = f"{bottom_margin}\\baselineskip"
    result = element
    if hpos == "center":
        result = minipage(element, vmargin=vmargin)
    elif hpos == "left":
        result = minipage("\\hfill" + element, vmargin=vmargin)
    elif hpos == "right":
        result = minipage(element + "\\hfill", vmargin=vmargin)
    return result

def make_caption_text(number, label, text, font_symbol, font_size):
    caption = None
    if number:
        caption = kutil.caption_marker(label, text)
    elif text:
        # caption = text   # f"{{\\small \\it \\par {caption_text}}}"
        caption = text

    font_symbol = "r"
    font_size = 1.2

    caption = font.tex_fontify(caption, font_symbol, font_size)
    return caption

def add_caption(element, caption_label, number, caption_text, latex_width,
                hpos="center", side="bottom", font_symbol="i", font_size=.9):
    top_margin = .75 if "includegraphics" in element else .5
    caption = make_caption_text(number, caption_label, caption_text, font_symbol, font_size)
    if caption:
        if side in {"left", "right"}:
            caption_margin_size = "12pt"
            caption_margin = f"\\hspace{{{caption_margin_size}}}"
            caption_width = f"\\textwidth - {latex_width} - {caption_margin_size}"
        else:
            #caption_margin = "\\vspace*{8pt}"
            # caption_margin = "\\vstrut{.25\\baselineskip}\n"
            pass

        if side == "left":
            element = minipage(minipage(caption, caption_width, center=False) + #, vmargin=top_margin) +
                               caption_margin +
                               minipage(element, latex_width))
        elif side == "right":
            element = minipage(minipage(element, latex_width) + 
                               caption_margin +
                               minipage(caption, caption_width, center=False))
        elif side == "bottom":
            element = minipage(element + "\n\\vstrut{1.33\\baselineskip}" + caption,
                               # minipage(element, vertical="t") +
                               # caption_margin + "\n" +
                               # minipage(caption),
                               latex_width, vertical="t")
        elif side == "top":
            element = minipage(caption + "\n" + element,
                               # minipage(caption, vertical="t") +
                               # caption_margin + "\n" +
                               # minipage(element),
                               latex_width, vertical="t")
    return caption_wrapper(element, hpos)
