import logging
from logging import Logger

from devicemanager.model import Configs

from cfgtools import read
from helper import config_logger


class Configurator(object):

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

        self.config = Configs()
        self.config.loader_path = loader_path
        self.reader = read(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 = "DeviceManager."
        sectors_config = {}
        sectors = self.reader.find_group(self.group + "Sectors")
        for sector in sectors.groups:
            sector_name = sector.name.upper()
            if sector_name not in sectors_config:
                sectors_config[sector_name] = {}
            for key in sector.keys:
                device_type = key.name.upper()
                if device_type in sectors_config[sector_name]:
                    self.logger.info("Device manager sector loader key duplicated - {}{}".format(sector.name, key.name))

                find_key = "{}Sectors.{}.{}".format(self.group, sector.name, key.name)
                values = self.reader.find_values(find_key)
                values = values[0] if device_type != "EXCLUDEDPOS" else values
                sectors_config[sector_name][device_type] = values

        self.config.sector_config = sectors_config
        return self.config

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

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

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

        return self.logger

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

        return value.lower() == "true"
