#!/usr/bin/env python

## \file desktop.py
#  \brief Entrypoint file for desktop versions of the Seagull Game.

import argparse
import os
import pathlib
import sys
import threading
import webview

import flask
import fs.tree
try:
    import pyi_splash
except ImportError:
    class NullModule():
        def update_text(self, *args, **kwargs):
            pass

        def close(self):
            pass
    
    pyi_splash = NullModule()

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

core.desktop_mode = True
sig_exit = threading.Event()

argp = argparse.ArgumentParser("seagull")
argp.add_argument("-d", "--debug", action="store_true", help="Launches the game in \"debug mode\".")
argo = argp.parse_args()

@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/desktop-structuredclone.js"), False))
        core.base_context["scripts"].insert(1, (core.app.url_for("static", filename="js/seagull-desktop.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__":
    try:
        pyi_splash.update_text("Determining storage directory")
        if sys.platform.startswith("win"):
            storage_dir = pathlib.Path(os.environ["APPDATA"]) / "seagull"
        elif sys.platform.startswith("darwin"): # macos
            storage_dir = pathlib.Path(os.environ["HOME"]) / "Library/Application Support/seagull"
        else:
            # TODO: check if XDG env vars are set and prioritize those
            storage_dir = pathlib.Path(os.environ["HOME"]) / ".local/share/seagull"
        desktop.path_storagedir = storage_dir

        pyi_splash.update_text("Loading VFS")
        gamedata.vfs.load_data_source("basepak")
        gamedata.vfs.load_data_source("seagull.pak", proto="zip")

        if argo.debug:
            desktop.api.debug_mode = True
        
        pyi_splash.update_text("Validating game rules")
        core.validate_xml_files()
        pyi_splash.update_text("Starting browser shell")
        storage_dir.mkdir(exist_ok=True, parents=True)
        webview.create_window("Seagull Game", core.app, js_api=desktop.api, width=1280, height=720)
        pyi_splash.close()
        webview.start(private_mode=False, storage_path=storage_dir.as_posix(), debug=True if argo.debug else False)
    except KeyboardInterrupt:
        core.log.info("Goodnight, moon ...")
        sig_exit.set()
        sys.exit(0)