#!/usr/bin/env python
# -*- coding: utf-8 -*-

from jinja2 import Environment, FileSystemLoader, UndefinedError, TemplateNotFound, TemplateSyntaxError, TemplateAssertionError
import argparse, sys


def render(project_path, template_path, autoescape):
    env = Environment(loader=FileSystemLoader(project_path), autoescape=autoescape)
    template = env.get_template(template_path)
    result = template.render()
    sys.stdout.write(result.encode('utf-8'))


if __name__ == "__main__":
    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('project_path',
        help="The SiteFlow project absolute path")
    parser.add_argument('template_path',
        help="The template\'s path, relative to the project's root")
    parser.add_argument('--autoescape',
        action='store_true',
        help='Autoescape for XML/HTML')
    args = parser.parse_args()
    
    # Render...
    try:
        render(args.project_path, args.template_path, args.autoescape)
    # ... or output errors
    except TemplateNotFound as e:
        sys.exit(u"Template {name} not found.".format(name=e.name))
    except TemplateSyntaxError as e:
        sys.exit(u"Syntax error in template {name} at line {lineno}:\n{message}".format(message=e.message, lineno=e.lineno, name=e.name))
    except TemplateAssertionError as e:
        sys.exit(u"Error in template {name} at line {lineno}:\n{message}".format(message=e.message, lineno=e.lineno, fname=e.name))
    except UndefinedError as e:
        sys.exit(u"Undefined error:\n{message}".format(message=e.message))