#!/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/2018/wiki/api.php?action=parse&page=Assembly:C3Space&format=json&prop=text'

FLIGHTPLAN_URL = 'https://frab.txtfile.eu/en/34c3-ffc/public/schedule.json'
MISSION_CREW = ['INCO', 'ar3itrary']

STATIC_FILES_DIR = 'static/'
ARCHIVE_DIR = 'archive/'
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)

    if resp.ok:
        try:
            page = resp.json()['parse']
            render_to_file(jinja_env, 'index.html', page, 'index.html', output_dir)
        except ValueError:
            pass


def generate_flightplan(jinja_env, output_dir):
    resp = requests.get(FLIGHTPLAN_URL)

    if resp.ok:
        lectures = []
        days = resp.json()['schedule']['conference']['days']

        for day in days:
            for room in day['rooms'].values():
                for lecture in room:
                    persons = lecture['persons']
                    if any(person['public_name'] in MISSION_CREW for person in persons):
                        lecture['day'] = day['index']
                        lectures += [lecture]
        page = {
            'title': 'Flightplan',
            'schedule' : lectures
        }

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


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

    output_dir = 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)

    archive_dir = os.path.join(BASE_DIR, ARCHIVE_DIR)
    archive_dest = os.path.join(output_dir, ARCHIVE_DIR)
    copy_dir(archive_dir, archive_dest)


    template_dir = os.path.join(BASE_DIR, TEMPLATE_DIR)
    jinja_env = Environment(loader=FileSystemLoader(template_dir))

    generate_index(jinja_env, output_dir)
    #generate_flightplan(jinja_env, output_dir)

if __name__ == '__main__':
    main()
