import logging
import sys

from application.model import AuditEvent
from application.repository import MessageBusRepository
from cfgtools import read
from helper import config_logger
from syserrors import SE_CFGLOAD, SE_NOTFOUND


class Configurator(object):

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

        self.logger = None
        self.loader_path = loader_path
        self.cfg_reader = read(loader_path)
        self.cfg_group = None
        self.service_name = None
        self.required_services = "AuditLogger|StoreWideConfig"
        self.service_type = "DataPump"
        order_picture_url = "pump/sale/order-picture"
        self.views = {
            AuditEvent.PAID: order_picture_url,
            AuditEvent.VOID_ORDER: order_picture_url,
            AuditEvent.ORDER_REPROCESS: order_picture_url,
            AuditEvent.CLEAR_TENDERS: order_picture_url,
            AuditEvent.OPERATOR_LOGOUT: "pump/cash/close-drawer-v2",
            AuditEvent.PRODUCTION_ORDER: "pump/sale/production-order",
            AuditEvent.TABLE_CLOSED: "pump/sale/tablePicture",
            AuditEvent.CLOSE_STORE_DAY: "pump/????",
            AuditEvent.OPEN_STORE_DAY: "pump/?????",
        }
        self.pump_status_url = "pump/sale/pumpStatus"

        self.store_id = None
        self.store_division = None
        self.server_url = None
        self.api_key = None
        self.retry_wait = None
        self.fiscal_xml = None

    def configure_service_name(self):
        # type: () -> None

        self.service_name = self.cfg_group = str(self.cfg_reader.find_value("Identification.ComponentName"))

    def configure_logger(self):
        # type: () -> None

        config_logger(self.loader_path, self.service_name)
        self.logger = logging.getLogger(self.service_name)

    def read_configurations(self, pos_repository):
        # type: (MessageBusRepository) -> None

        try:
            self.logger.info("[START] Reading configurations")

            group = self.service_name + ".{}"

            self.store_id = pos_repository.read_sw_config("Store.Id")
            self.store_division = pos_repository.read_sw_config("Store.Division")

            self._read_api_key(pos_repository, group)
            self._read_server_url(pos_repository, group)

            self.retry_wait = int(self.cfg_reader.find_value(group.format("retryWait"), "10000"))
            self.fiscal_xml = self.cfg_reader.find_value(group.format("fiscalXml"), "true").lower() == "true"

            self.logger.info("[END] Reading configurations")
        except Exception as _:
            self.logger.exception("[{}] Error reading configuration file".format(self.service_name))
            sys.exit(SE_CFGLOAD)

    def _read_api_key(self, pos_repository, group):
        # type: (MessageBusRepository, str) -> None

        self.api_key = self.cfg_reader.find_value(group.format("OverwrittenApiKey"))
        if not self.api_key:
            self.api_key = pos_repository.read_sw_config("BackOffice.ApiKey")

    def _read_server_url(self, pos_repository, group):
        # type: (MessageBusRepository, str) -> None

        self.server_url = self.cfg_reader.find_value(group.format("OverwrittenServerURL"))
        if not self.server_url:
            self.server_url = pos_repository.read_sw_config("BackOffice.ServerURL")
        if not self.server_url:
            self.logger.error("[{}] Configuration error: server_url is undefined".format(self.service_name))
            sys.exit(SE_NOTFOUND)
        if not self.server_url.endswith("/"):
            self.server_url += "/"

        self.logger.info("POST URL: {}".format(self.server_url))
