import os
from typing import (
    Any,
    Optional,
)

from cfgtools import read
from message_handler_builder import ConfigInfo


class Configurator(object):
    def __init__(
        self,
        loader_path: [str],
    ):
        self.loader_path = loader_path
        self.reader = read(file_or_path=loader_path)

        self.component_name = None
        self.group = "EventManager."

    def read_loader_configs(self) -> ConfigInfo:
        self.component_name = self._find("Identification.ComponentName", "CustomEventManager")
        database_path = self._find("DatabasePath", "")
        max_worker_threads = int(self._find("MaxWorkerThreads", 10))
        maintenance_interval = int(self._find("MaintenanceInterval", 30))
        acked_events_ttl = int(self._find("AckedEventsTtl", 7))
        abandoned_events_ttl = int(self._find("AbandonedEventsTtl", 30))

        return ConfigInfo(
            database_path=self._get_databases_path(database_path),
            component_name=self.component_name,
            max_worker_threads=max_worker_threads,
            acked_events_ttl=acked_events_ttl,
            abandoned_events_ttl=abandoned_events_ttl,
            maintenance_interval=maintenance_interval * 1000 * 60,
        )

    def _get_databases_path(
        self,
        database_path: str,
    ) -> str:

        if database_path == "":
            comp_dir = os.path.dirname(self.loader_path)
            database_path = os.path.abspath(os.path.join(comp_dir, "..", "..", "databases", "event_manager.db"))

        if database_path.startswith("file:") == -1:
            database_path = f"file:///{database_path}"

        return database_path

    def _find(
        self,
        key: [str],
        default_value: Optional[Any] = None,
    ) -> Optional[str]:

        return self.reader.find_value(self.group + key, default=default_value)
