#!/usr/bin/env python
"""
A script to launch the Monopyly application.
"""
import os
import argparse
import time
import signal
import subprocess
import webbrowser
from pathlib import Path
from threading import Event

from flask import current_app


# Set the Flask environment variable
os.environ['FLASK_APP'] = 'monopyly'


def main(mode, host=None, port=None):
    # Initialize the database (force debug mode here, not during production)
    os.system('flask --debug init-db')
    run_app(mode, host, port)
    # Run the default web browser
    time.sleep(1)
    port = "5000" if port is None else port
    webbrowser.open(f"http://127.0.0.1:{port}/")
    wait_for_exit()


def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--host",
        help="The host address where the app will be run."
    )
    parser.add_argument(
        "--port",
        help="The port where the app will be accessible."
    )
    parser.add_argument(
        "mode",
        help="The runtime mode for the app; defaults to `development`.",
        choices=["development", "production"],
    )
    return parser.parse_args()


def run_app(mode, host=None, port=None):
    """Run the Monopyly application."""
    command = ["flask", "run"]
    if mode == "development":
        command.insert(1, "--debug")
    if host:
        command.extend(["--host", host])
    if port:
        command.extend(["--port", port])
    server = subprocess.Popen(command)


def wait_for_exit():
    """Wait for the exit command (e.g., keyboard interrupt) to be issued."""
    for sig in ("TERM", "HUP", "INT"):
        signal.signal(getattr(signal, "SIG"+sig), _quit)
    while not _exit.is_set():
        _exit.wait(1)


def _quit(signo, _frame):
    """Send the signal to quit the app."""
    print('\nClosing the Monopyly app...')
    _exit.set()


_exit = Event()

if __name__ == "__main__":
    args = parse_arguments()
    main(args.mode, host=args.host, port=args.port)

