#!/usr/bin/env python

import gevent.monkey
gevent.monkey.patch_all()

import pathlib
import sys
import threading

import flask
from gevent.pywsgi import WSGIServer

from pylocal import core, actions, dev, gamedata, items, tick, upgrades

sig_exit = threading.Event()

@core.app.route("/")
def index():
    if not core.base_context_live:
        core.render_base_context()
        core.base_context["scripts"].insert(0, (core.app.url_for("static", filename="js/seagull-web.js"), False))
    gamedata.vfs.copy_out("templates/main_page.j2", dest=core.path_appdir.as_posix())
    return flask.render_template("main_page.j2", **core.base_context)

if __name__ == "__main__":
    gamedata.vfs.load_data_source("basepak")
    gamedata.vfs.load_data_source("seagull.pak", proto="zip")

    core.validate_xml_files()
    #core.app.run("0.0.0.0", 1337)
    try:
        http_server = WSGIServer(('', 80), core.app)
        http_server.serve_forever()
    except KeyboardInterrupt:
        core.log.info("Goodnight, moon ...")
        sig_exit.set()
        sys.exit(0)