# Main script
import logging
import os
import signal
import sys

from core.cleanup import CLEANUP_TIMER
from core.config import SERVER_OWNER_CALLSIGN, LOG_LEVEL
from core.constants import SOFTWARE_VERSION
from core.data_providers import DATA_PROVIDERS
from core.data_store import DATA_STORE
from core.status_reporter import StatusReporter
from server.webserver import WEB_SERVER

# Globals
run = True

def shutdown(_signum=None, _frame=None):
    """Shutdown function"""

    global run

    logging.info("Stopping program...")
    WEB_SERVER.stop()
    DATA_PROVIDERS.stop()
    CLEANUP_TIMER.stop()
    DATA_STORE.close()
    os._exit(0)


# Main function
if __name__ == '__main__':
    # Set up logging
    root = logging.getLogger()
    root.setLevel(LOG_LEVEL)
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(LOG_LEVEL)
    formatter = logging.Formatter("%(levelname)s : %(message)s")
    handler.setFormatter(formatter)
    root.handlers.clear()
    root.addHandler(handler)

    logging.info("Starting...")
    logging.info(
        "This is Spothole version " + SOFTWARE_VERSION + ". This instance is run by " + SERVER_OWNER_CALLSIGN + ".")

    # Shut down gracefully on SIGINT
    signal.signal(signal.SIGINT, shutdown)

    # Set up data store
    DATA_STORE.setup()
    CLEANUP_TIMER.setup(cleanup_interval=60)
    CLEANUP_TIMER.start()

    # Set up and start data providers
    DATA_PROVIDERS.setup()
    DATA_PROVIDERS.start()

    # Set up and start status reporter
    status_reporter = StatusReporter(run_interval=5)
    status_reporter.start()

    # Set up the web server
    WEB_SERVER.setup()

    # Run the web server. This is the blocking call that keeps the application running in the main thread, so this must
    # be the last thing we do. web_server.stop() triggers an await condition in the web server which finishes the main
    # thread.
    WEB_SERVER.start()
