import os
import glob


def beamer_nup(pdf_file, nup=6, output=None, a4paper=True):
    # pdf_file = pdf_file[:-4] + ".pdf"
    if nup not in [1, 2, 3, 4, 6]:
        assert False

    jinja = os.path.dirname( __file__ ) + "/../../jinja"
    if os.path.isdir(jinja):
        js = {}
        for name in glob.glob(jinja + "/*.tex"):
            with open(name, 'r') as f:
                js[os.path.basename(name)[:-4] ] = f.read()

        s = ""
        for k, v in js.items():
            v = v.replace("\\", "\\\\")

            s += f'{k} = """\n' + v + '\n"""' + "\n"

        with open(os.path.dirname(__file__) + "/jinjastrings/generated.py", 'w') as f:
            s = "# WARNING! THIS FILE IS AUTOMATICALLY GENERATED! ALL CHANGES WILL BE WIPED. SEE JINJA DIRECTORY\n"*10  + s
            f.write(s)



    from slider.jinjastrings.generated import lecture_collector_partial

    import jinja2

    import tempfile
    # tempfile.gettempdir()
    tmp = tempfile.TemporaryDirectory().name
    os.mkdir(tmp)
    import shutil
    dest_pdf = tmp + "/" + os.path.basename(pdf_file)
    shutil.copyfile(pdf_file, dest_pdf)

    import jinja2
    data = {'a4': False,
            'twoup': False,
            'sixup': False,
            'a4paper': a4paper}
    if nup == 1:
        data['a4'] = True
    if nup == 2:
        data['twoup'] = True
    if nup == 3:
        data['threeup'] = True
    if nup == 4:
        data['fourup'] = True
    if nup == 6:
        data['sixup'] = True
    data['frame'] = True

    data['pdffiles'] = [os.path.basename(dest_pdf)]

    # data = {'hello': 'world'}
    print(tmp)
    s = jinja2.Environment().from_string(lecture_collector_partial).render(data)

    with open(tmp +"/nup.tex", 'w') as f:
        f.write(s)

    from slider import latexmk
    latexmk(tmp +"/nup.tex", shell=True)

    if output == None:
        output = os.path.dirname(pdf_file) + "/" + os.path.basename(pdf_file)[:-4] + f"_{nup}up.pdf"
    shutil.move(tmp +"/nup.pdf", output)
    print(tmp)
    print("[Beamer-nup] Wrote output to", output)
    return output



if __name__ == "__main__":
    beamer_nup("../../examples/new_project/index.pdf")

