import sys
import re
from argparse import ArgumentParser, FileType
from qcard import *
import qcard.latex as latex

parser = ArgumentParser(description="Generate Flashcards")
parser.add_argument('infile', nargs='?', type=FileType('r'), default=sys.stdin)
parser.add_argument('-o', '--outfile', nargs='?', type=FileType('w'),
                    default='./.cards')
parser.add_argument('-t', '--tags', nargs='?', type=str,
                    default='')

inp = parser.add_mutually_exclusive_group(required=True)
inp.add_argument('-l', '--latex', action="store_true")

out = parser.add_mutually_exclusive_group(required=True)
out.add_argument('-a', '--anki', action="store_true")

args = parser.parse_args()


cmd_re = re.compile("^\s*%\s+@(?P<cmd>\w+).*$")
th_re = re.compile("\\newtheorem\*\{\w+\}\{(?P<title>)\}")


deck = []

TAG_PARSERS = {
    'th': latex.TheoremParser,
    #'ctree': latex.,
    'algo': latex.AlgorithmParser,
}

stream = enumerate(args.infile)

i, line = next(stream)
while line:
    m = cmd_re.match(line)
    if m:
        cmd = m.group('cmd')
        parser = TAG_PARSERS.get(cmd, None)
        if parser:
            fields = parser(stream).parse()
            deck.append(AnkiCard(fields))

    try:
        i, line = next(stream)
    except StopIteration:
        break

# Generate tags
tags = " ".join(args.tags.split(','))
if tags: args.outfile.write("tags:" + tags + "\n\n")

# Generate cards
for c in deck:
    args.outfile.write(c.generate(format='latex') + "\n\n")

# vim: set filetype=python:
