import os
import datetime
import json
from django.apps import AppConfig
from django.conf import settings

from simulation import SimulationThread

class TrafficlightfrontendConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'trafficlightfrontend'
    initialized = False
    simulation_thread = None

    # Note as per documentation, may be called more than once
    # Therefore needs to be idempotent or use flag
    def ready(self):
        # Ensure RUN_MAIN to avoid starting thread on runserver "change watchdog" instance
        if TrafficlightfrontendConfig.initialized or os.environ.get("RUN_MAIN") is None:
            return

        # print("Traffic Light Frontend: initialization.")
        # print("Current working directory: {}".format(os.getcwd()))

        periods = json.load(open(os.path.join(settings.BASE_DIR, settings.SIMULATION_DATA_FILE)))

        SimulationThread.initialize(periods, start_time=datetime.time.fromisoformat(settings.SIMULATION_START_TIME), time_factor=settings.SIMULATION_TIME_FACTOR)
        SimulationThread.get_instance().start()

        TrafficlightfrontendConfig.initialized = True
