#!/usr/bin/env python3

import os
import sys
import shutil
import requests
from jinja2 import Environment, FileSystemLoader

from staticfiles import copy_dir

WIKI_URL = "https://events.ccc.de/congress/2017/wiki/api.php?action=parse&page=Assembly:CSOC&format=json&prop=text"

STATIC_FILES_DIR = "static/"
TEMPLATE_DIR = "templates"

BASE_DIR = os.path.dirname(os.path.abspath(__file__))


def render_to_file(jinja_env, template, context, url, output_dir):
    template = jinja_env.get_template(template)
    result = template.render(context)

    out_path = os.path.join(output_dir, url)
    out_dir = os.path.dirname(out_path)
    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)

    print("Rendering %s" % out_path)

    out_file = open(out_path, 'wb')
    out_file.write(result.encode('utf-8'))
    out_file.close()


def generate_index(jinja_env, output_dir):
    resp = requests.get(WIKI_URL)
    page = resp.json()['parse']

    render_to_file(jinja_env, 'index.html', page, 'index.html', output_dir)


def main():
    if len(sys.argv) != 2:
        print("Usage: %s" % sys.argv[0])
        sys.exit(-1)

    output_dir = os.path.dirname(os.path.abspath(sys.argv[1]))

    if not os.path.exists(output_dir):
        os.mkdir(output_dir)

    static_dir = os.path.join(BASE_DIR, STATIC_FILES_DIR)
    copy_dir(static_dir, output_dir)

    jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_DIR))
    generate_index(jinja_env, output_dir)

if __name__ == '__main__':
    main()
