import re
import os
import time
import subprocess
import tempfile

LATEXMPLATE = r"""
\documentclass[11pt]{article}
\usepackage[fourier]{PNS}
\usepackage{tikz}
\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}
}
\begin{document}
\thispagestyle{empty}
SOURCE
\end{document}
"""

def add(path: str, line_num: int):
    """Given a path to a file, import the tikz
    picture defined starting on the gtiven line into the database.
    """
    
    with open(path) as f:
        lines = f.readlines()
    folder, filename = os.path.split(path)
    modified = time.ctime(os.path.getmtime(path))
    
    # figure out how many lines we need to consider
    for n in range(line_num, len(lines)):
        if re.search(r'\\end{tikzpicture}', lines[n]):
            break
    source = "".join(lines[line_num : n + 1])
    
    # We'd now like to pipe this through latexindent
    tdir = tempfile.gettempdir()
    tdir = '/Users/saeta/tmp/tex'
    os.chdir(tdir)
    p = 'src.tex'
    tmp = open(p, 'w').write(source)
    subprocess.run(['latexindent', p, '-o', 'fixed.tex'])
    formatted = open('fixed.tex', 'r').read()
    formatted = formatted.replace('\t', '  ')
    
    # Generate image
    open('img.tex', 'w').write(LATEXMPLATE.replace('SOURCE', formatted))
    subprocess.run(['pdflatex', 'img'])
    
    subprocess.run(['pdfcrop', 'img', 'cropped.pdf'])
    subprocess.run(['convert', '-density', '150', 'cropped.pdf', 'cropped.png'])
    
    


if __name__ == '__main__':
    add('/Users/saeta/Documents/Courses/p24a/2022/hw/hw07-sol.tex', 118)

    