import re
from pathlib import Path
from subprocess import run
import os

LATEXTEMPLATE = r"""
\documentclass[11pt]{article}
\usepackage[fourier]{PNS}
\usepackage{tikz}
\usepackage{lipsum}
\usetikzlibrary{arrows.meta,calc,decorations.pathmorphing}
\tikzset{%
every picture/.style={>=Stealth},
vel/.style={->,line width=2pt,color=DarkBlue},
vector/.style={->,line width=2pt, color=SlateBlue},
force/.style={line width=1.5pt,color=blue,->},
coord/.style={color=green!40!black,->},
accel/.style={->,line width=2.5pt,color=gray},
photon/.style={line width=1.5pt,color=DarkRed,decorate,decoration={snake,post length=0.1in}},
spring/.style={decorate,decoration={coil,aspect=0.3,segment length=2mm,amplitude=2mm}},
traj/.style={dashed, color=gray, line width=1pt},
component/.style={->,dashed,line width=1pt, color=SlateGray}
}
\definecolor{trace01}{rgb}{0.5,0,0}
\definecolor{trace02}{rgb}{0,0,0.5}
\definecolor{trace03}{rgb}{0,0.5.0}
\definecolor{trace04}{rgb}{0.5,0.5,0}
\definecolor{trace05}{rgb}{0.4,0.3,0}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18,width=3in}
DEFS
\begin{document}
\thispagestyle{empty}
SOURCE
\end{document}
"""

class Texer:
    HOME = Path(__file__).parent.parent

    def __init__(self, **kwargs):
        self.template = kwargs.get('template', LATEXTEMPLATE)
        self.code = kwargs.get('code', '')
        self.defs = kwargs.get('defs', '')
        self.cleanup()
        self.png = None
        self.source = None
        self.error = None
        self.escape = kwargs.get('esc', True)
        self.compile()

    def cleanup(self):
        for path in ("tmp.tex", "tmp.pdf", "crop.pdf", "crop.png"):
            try:
                os.remove(path)
            except:
                pass

    def compile(self):
        savepath = os.getcwd()
        os.chdir(self.HOME)
        tmp = self.template.replace('SOURCE', self.code).replace('DEFS', self.defs)
        self.source = tmp.replace('\r\n', '\n')
        path = self.HOME / 'tmp.tex'
        open(path, 'w').write(self.source)
        cmd = ['pdflatex', '-interaction=nonstopmode', str(path)]
        if self.escape:
            cmd.insert(1, '-shell-escape')
        res = run(cmd, capture_output=True)
        log = res.stdout.decode()
        pdf = "Output written on tmp.pdf" in log
        self.error = re.findall(r'^!.*$|Latex Error:.*$', log, re.M)
        if pdf:
            self.crop(path)
        os.chdir(savepath)

    def crop(self, path):
        cmd = ['pdfcrop', str(path.with_suffix('.pdf')),
                  str(path.with_name('crop.pdf'))]
        res = run(cmd, capture_output=True)
        if res.returncode == 0:
            res = run(['convert', '-density', '150', 'crop.pdf',
                       'crop.png'])
            if res.returncode == 0:
                try:
                    self.png = open('crop.png', 'rb').read()
                except:
                    self.png = open('crop-0.png', 'rb').read()


if __name__ == '__main__':
    CODE = r"""
    \begin{minted}{python}
    import numpy as np
    import matplotlib.pyplot as plt

    fig, ax = plt.subplots()
    x = np.linspace(0,10,11)
    ax.plot(x, np.sqrt(x))
    plt.show()
    \end{minted}
    """
    DEFS = r"""
    \usepackage{minted}
    """
    texer = Texer(code=CODE, defs=DEFS, esc=True)
    texer.compile()
    if self.png:
        print("success!")






