'''
Created on Feb 19, 2016

@author: mike
'''
from __future__ import print_function

import codecs
import re
import argparse

TEMPLATE = r'''

\documentclass{article}
\usepackage{polyglossia}
\usepackage{xltxtra}
\usepackage{testhyphens}
\setdefaultlanguage{churchslavonic}
\newfontfamily\churchslavonicfont[Script=Cyrillic]{PonomarUnicode.otf}

\begin{document}

$BODY$

\begin{checkhyphens}
$CHECKHYPHENS$
\end{checkhyphens}

\end{document}
'''


def main_generate(args):

    words = list(read_words(args.dictionary))
    
    body= '\n'.join('\\showhyphens{%s}' % x for x in words)
    
    checkhyphens = '\n'.join(words)

    text = re.sub(r'\$BODY\$', body, TEMPLATE)
    text = re.sub(r'\$CHECKHYPHENS\$', checkhyphens, text)
    
    with codecs.open(args.output, 'w', 'utf-8') as f:
        f.write(text)


def read_words(fname, strip_hyphen=True):
    
    rex = re.compile(r'\d')
    if strip_hyphen:
        rex = re.compile(r'[\-\d]')

    with codecs.open(fname, 'r', 'utf-8') as f:
        for l in f:
            l = l.strip()
            if not l:
                continue
            if l.startswith('#') or l.startswith('%'):
                continue
            l = rex.sub('', l)
            yield l


def main_extract(args):
    
    with codecs.open(args.output, 'w', 'utf-8') as f:
        for x in generatehyps(args.log):
            f.write(x + '\n')


def generatehyps(fname):
    with codecs.open(fname, 'r', 'utf-8') as f:
        
        expect = False
        for l in f:
            l = l.strip()
            if expect > 0:
                expect -= 1

            if expect == 1:
                expect = 0
                yield l.split()[1]
            else:
                if re.search(r'showhyphens: \*\*\*', l):
                    expect = 4


def main_strip_weights(args):

    words = list(read_words(args.input, strip_hyphen=False))

    with codecs.open(args.output, 'w', 'utf-8') as f:
        for word in words:
            f.write(word + '\n')
    
    return 0


def main():
    parser = argparse.ArgumentParser(description='Utility to compare training dictionary with actual hyphenations as generated by TeX')
    sub = parser.add_subparsers(help='Commands', dest='cmd')
    
    parser_generate = sub.add_parser('generate', help='Generate LaTex file with all dictionary words')
    parser_generate.add_argument('dictionary', help='input dictionary file')
    parser_generate.add_argument('output', help='output LaTeX file')
    
    parser_extract = sub.add_parser('extract', help='Extract actual TeX hyphenations from LaTeX log file')
    parser_extract.add_argument('log', help='input LaTeX log file')
    parser_extract.add_argument('output', help='output hyphenation dictionary as extracted from log')

    parser_strip_weights = sub.add_parser('strip_weights', help='Strips weights (numbers) from dictionary')
    parser_strip_weights.add_argument('input', help='input dictionary file')
    parser_strip_weights.add_argument('output', help='output dictionary with numeric weights stripped off')

    args = parser.parse_args()
    
    if args.cmd == 'generate':
        parser.exit(main_generate(args))
    elif args.cmd == 'extract':
        parser.exit(main_extract(args))
    elif args.cmd == 'strip_weights':
        parser.exit(main_strip_weights(args))
    else:
        parser.error('Missing or unrecognized command')


if __name__ == '__main__':
    main()

