#! /usr/bin/env python
import re, os, sys

def convert(inp, outp, outputdir, basename):
    match_comment = re.compile("<!-- .* -->$").match
    match_default = re.compile("#seqdiag default: *(.*)").match
    match_diag = re.compile('#(seq|block)diag *([^ ]*) *("[^"]*")? *{').match
    default = None
    outp.write("<!-- generated by ../../tools/undiag. DON'T CHANGE (change .mdx source) -->\n")
    for line in inp:
        m = match_comment(line)
        if m:
            continue
        m = match_default(line)
        if m:
            default = m.group(1)
            continue
        m = match_diag(line);
        if m:
            # svg seems to get scaled by the browser, lets take png
            imagename = basename + "_" + m.group(2) + ".png"
            graph = os.popen("%sdiag --antialias --font=/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf -o %s -"
                             % (m.group(1), os.path.join(outputdir, imagename)), "w")
            graph.write("{\n")
            if default:
                graph.write(default)
                graph.write("\n")
            for line in inp:
                graph.write(line)
                if line.startswith("}"):
                    break
            graph.close()
            title = m.group(3) or ""
            if title:
                title = " " + title
            outp.write("\\image html %s%s\n" % (imagename, title))
            continue
        outp.write(line)

if __name__ == "__main__":
    for path in sys.argv[1:]:
        basedir, filename = os.path.split(path)
        basename = os.path.splitext(filename)[0]
        outputdir = os.path.join(basedir, "preprocessed")
        output = os.path.join(outputdir,basename+".md")
        convert(open(path), open(output, "w"), outputdir, basename)
