import logging
import os
import shutil


from logging import Logger
import cfgtools

from cfgtools import Group
from systools import sys_parsefilepath

from helper import (
    config_logger,
    import_pydevd,
)
from mbcontextmessagehandler import (
    MbContextMessageBus,
    MbContextMessageHandler,
)
from messagehandlerbuilder import ElectronicPaymentMessageHandlerBuilder
from msgbus import MBEasyContext

from model import SitefClisitefDoesNotExistsException

COMPONENT_NAME = "ElectronicPayment"
REQUIRED_SERVICES = "StoreWideConfig"


def main():
    loader_path = os.environ["LOADERCFG"]

    import_pydevd(loader_path, 9132, False)
    config_logger(loader_path, COMPONENT_NAME, max_files=100, max_size=12582912, add_error_handler=True)

    logger = logging.getLogger(COMPONENT_NAME)
    config = cfgtools.read(loader_path).find_group("ElectronicPayment")  # type: Group

    _get_sitef_config(logger)

    try:
        message_bus = MbContextMessageBus(MBEasyContext(COMPONENT_NAME))
        message_handler_builder = ElectronicPaymentMessageHandlerBuilder(message_bus, config, logger)
        message_handler = MbContextMessageHandler(
            message_bus,
            config.find_value("ServiceName"),
            "Payment",
            REQUIRED_SERVICES,
            message_handler_builder)
        return message_handler.handle_events()
    except Exception as _:
        logger.exception('exception on start')
        raise


def _get_sitef_config(
    logger,     # type: Logger
):
    # type: (...) -> None

    try:
        bundle_dir_path = _get_bundle_dir_path()

        electronic_payment_sitef_dlls_dir = os.path.join(bundle_dir_path, "electronic-payment/dll/sitef/")
        dir_not_exists = not os.path.exists(electronic_payment_sitef_dlls_dir)
        if dir_not_exists:
            logger.info("Electronic payment sitef dlls path does not exists")
            return

        electronic_payment_sitef_config_path = os.path.join(electronic_payment_sitef_dlls_dir, "clisitef.ini")
        file_already_exists = os.path.isfile(electronic_payment_sitef_config_path)
        if file_already_exists:
            logger.info("Electronic payment clisitef.ini already exists")
            return

        sitef_config_file = os.path.join(bundle_dir_path, "sitef/lib/clisitef.ini")
        file_exists = os.path.isfile(sitef_config_file)
        if not file_exists:
            raise SitefClisitefDoesNotExistsException("Sitef clisitef.ini does not exists")

        shutil.copy(sitef_config_file, electronic_payment_sitef_dlls_dir)
    except Exception as _:
        logger.exception("Error getting clisitef.ini")


def _get_bundle_dir_path():
    # type: (...) -> str

    hv_data_dir = sys_parsefilepath("{HVDATADIR}")
    bundle_dir_path = os.path.join(hv_data_dir, "bundles")
    return bundle_dir_path
