#!/usr/bin/python3
import os
import shutil
import tarfile
import time

from argparse import ArgumentParser
from jinja2 import Environment, PackageLoader, select_autoescape
from config import context

PROJECT_FOLDER = os.path.dirname(__file__)

def dev(args, output):
    while True:
        time.sleep(0.5)
        render(args, output, quiet=True)


def render(args, output, quiet=False):
    # do build folder
    if os.path.exists(output):
        shutil.rmtree(output)

    if not quiet:
        print("copying static folder")
    try:
        shutil.copytree(os.path.join(PROJECT_FOLDER, 'static'), output)
    except Exception:
        pass

    # build environement
    env = Environment(
        loader=PackageLoader("export", 'templates'),
        autoescape=select_autoescape(['html'])
    )
    templates_folder = os.path.join(PROJECT_FOLDER, 'templates')
    for root, dirs, templates in os.walk(templates_folder):
        if root == os.path.join(templates_folder, 'meta'):
            continue
        for template_name in templates:
            template_absolute_path = os.path.join(root, template_name)
            template_file = template_absolute_path[len(templates_folder) + 1:]
            if not quiet:
                print('processing ' + template_file)
            page = template_name[:-len('.html')]
            template = env.get_template(template_file)
            compiled_template = template.render(page=page, **context)
            create_folder(output, template_file)
            with open(os.path.join(output, template_file), mode='w') as fp:
                fp.write(compiled_template)


def create_folder(container, template_file):
    split_path = template_file.split(os.path.sep)
    base_path = container
    for folder in split_path[:-1]:
        full_path = os.path.join(base_path, folder)
        if not os.path.exists(full_path):
            os.mkdir(full_path)


if __name__ == '__main__':
    parser = ArgumentParser(description="Build website")
    parser.add_argument('-o', '--output', default='build',
                        help="Output folder or file")
    parser.add_argument('-f', '--format', default="folder",
                        choices=("gzip", "folder", 'dev'),
                        help="Format output (either gzip, dev or folder)")
    parser.add_argument('-q', '--quiet', default=False,  action='store_true')
    args = parser.parse_args()
    output = args.output if args.format != 'gzip' else '_build'
    render(args, output, args.quiet)
    # compress
    if args.format == 'gzip':
        with tarfile.open(args.output, "w:gz") as tar:
            tar.add(output, arcname=os.path.basename(output))
        shutil.rmtree(output)
    elif args.format == 'dev':
        dev(args, output)
        shutil.rmtree(output)
