#!/usr/bin/env python3

import json
import logging
import pathlib
import queue
import threading

from . import config
from . import controller
from . import dect
from . import routing
from . import ywsd

logger = logging.getLogger("fieldpoc.fieldpoc")

class FieldPOC:
    config = None
    extensions = None

    def __init__(self, config_file_path, extensions_file_path):
        logger.info("loading configuration")
        self.config_file_path = pathlib.Path(config_file_path)
        self._load_config()
        self.extensions_file_path = pathlib.Path(extensions_file_path)
        self._load_extensions()

        logger.info("initialising queues")
        self.queues = {
            "controller": queue.Queue(),
            "dect": queue.Queue(),
            "routing": queue.Queue(),
        }

        logger.info("initialising components")
        self._controller = controller.Controller(self)
        self._dect = dect.Dect(self)
        self._routing = routing.Routing(self)
        self._ywsd = ywsd.Ywsd(self)

    def queue_all(self, msg):
        """
            Send message to every queue
        """

        for queue in self.queues.values():
            queue.put(msg)

    def init(self):
        """
            Prepare some data structures.
            Run this once before using FieldPOC.
        """

        logger.info("initialize datastructures")

        self._ywsd.init()

        logger.info("initialization complete")

    def run(self):
        logger.info("starting components")

        self._controller_thread = threading.Thread(target=self._controller.run)
        self._controller_thread.start()

        self._dect_thread = threading.Thread(target=self._dect.run)
        self._dect_thread.start()

        self._routing_thread = threading.Thread(target=self._routing.run)
        self._routing_thread.start()

        self._ywsd_thread = threading.Thread(target=self._ywsd.run, daemon=True)
        self._ywsd_thread.start()

        logger.info("started components")

    def _load_config(self):
        self.config = config.Config(json.loads(self.config_file_path.read_text()))

    def _load_extensions(self):
        self.extensions = config.Extensions(json.loads(self.extensions_file_path.read_text()))