#!/home/dirk/bin/venv/bin/python
# -*- coding: UTF-8 -*-

import jinja2
import optparse
import os
import shutil
import time


TYPES = ['brief', 'merkblatt', 'präsentation']
TARGET_EXTENTION = '.tex'


def mkdir(path):
    """.. warning:: Needs to be documented
    """
    path=os.path.abspath(path)
    if not os.path.exists(os.path.dirname(path)):
        mkdir(os.path.dirname(path))
    if not os.path.exists(path):
        os.mkdir(path)
    return os.path.isdir(path)


def get_path_replace_list():
    HOME_PATH_REPLACEMENT = '~'
    rv = []
    home_path = os.getenv("HOME")
    rv.append( (home_path, HOME_PATH_REPLACEMENT) )
    for p in os.listdir(home_path):
        full_path = os.path.join(home_path, p)
        if os.path.islink(full_path):
            rv.append( (os.path.realpath(full_path), os.path.join(HOME_PATH_REPLACEMENT, p)) )
    rv.sort(reverse=True)
    return rv


template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'latex_doc', 'templates')
static_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'latex_doc', 'static')


if __name__ == "__main__":
    parser = optparse.OptionParser("usage: %%prog [options] folder_for_document")
    parser.add_option("-t", "--type", dest="type", default=None, type="string", help="|".join(TYPES))
    parser.add_option("-f", "--force", dest="force", action="store_true", default=False)
    (options, args) = parser.parse_args()
    if len(args) != 1 or options.type is None or options.type not in TYPES:
        parser.print_help()
    else:
        target_file = os.path.join(os.path.abspath('.'), args[0])
        if not target_file.endswith(TARGET_EXTENTION):
            target_file = os.path.join(target_file, os.path.basename(target_file) + TARGET_EXTENTION)
        full_path = target_file
        for original, replacement in get_path_replace_list():
            if full_path.startswith(original):
                full_path = replacement + full_path[len(original):]
                break
        full_path = full_path.replace('~', '$\\sim$').replace('_', '\_')
        full_folder = os.path.dirname(full_path)
        filename = os.path.splitext(os.path.basename(target_file))[0]
        short_date = time.strftime('%d.%m.%Y')
        #
        # Main Actions
        #
        latex_jinja_env = jinja2.Environment(
            block_start_string = '\BLOCK{',
            block_end_string = '}',
            variable_start_string = '\VAR{',
            variable_end_string = '}',
            comment_start_string = '\#{',
            comment_end_string = '}',
            line_statement_prefix = '%_',
            line_comment_prefix = '%#',
            trim_blocks = True,
            autoescape = False,
            loader = jinja2.FileSystemLoader(template_path)
        )
        if not os.path.exists(target_file) or options.force:
            mkdir(os.path.dirname(target_file))
            with open(target_file, 'w') as fh:
                fh.write(latex_jinja_env.get_template(options.type + TARGET_EXTENTION).render(
                    full_path=full_path, 
                    full_folder=full_folder, 
                    filename=filename, 
                    short_date=short_date))
            if options.type == 'merkblatt':
                shutil.copytree(os.path.join(static_path, options.type), os.path.join(os.path.dirname(target_file), 'icons'))
        else:
            print("File exists. Use option -f to create file")