import logging

from logging import Logger
from typing import Optional

from cfgtools import read
from helper import config_logger

from services.model import Configs


class Configurator(object):

    def __init__(
        self,
        loader_path,            # type: str
        databases_path,         # type: str
        backup_databases_path,  # type: str
    ):
        # type: (...) -> None

        self.config = Configs()
        self.config.loader_path = loader_path
        self.config.databases_path = databases_path
        self.config.backup_databases_path = backup_databases_path
        self.reader = read(file_or_path=loader_path)
        self.group = None
        self.logger = None

    def read_loader_configs(
        self,
    ):
        # type: (...) -> Configs

        self.configure_loggers()
        self.config.component_name = self.reader.find_value("Identification.ComponentName")
        self.group = "Alerts"
        alerts_group = self.reader.find_group(self.group)
        alerts_config = {}
        for key in alerts_group.keys:
            alerts_config[key.name] = key.values[0] if len(key.values) == 1 else key.values
        self.config.alerts = alerts_config
        self.config.alerts[u"EndPoints"] = {
            u"ConfiguredAlerts": str(self._get_config("EndPoints.ConfiguredAlerts"))
        }

        return self.config

    def configure_loggers(
        self,
    ):
        # type: (...) -> None

        config_logger(
            loader_path=self.config.loader_path,
            log_name="Alerts",
            max_size=10485760,
            max_files=15,
        )
        self.logger = logging.getLogger(name="Alerts")

    def get_loggers(
        self,
    ):
        # type: (...) -> Logger

        return self.logger

    def _get_config(
        self,
        key,          # type: str
        array=False,  # type: Optional[bool]
    ):
        # type: (...) -> str

        path = self.config.component_name + "." + key
        return self.reader.find_values(path) if array else self.reader.find_value(path)

    @staticmethod
    def _is_true(
        value,  # type: str
    ):
        # type: (...) -> bool

        return value.lower() == "true"
