from parallels.core.logging import get_logger
from parallels.core.actions.base.customer_action import CustomerAction
from parallels.plesk import messages
from parallels.plesk.actions.hosting_settings.utils import is_copy_external_id_disabled

logger = get_logger(__name__)


class SetCustomersExternalId(CustomerAction):
    def get_description(self):
        return messages.ACTION_SET_CUSTOMERS_EXTERNAL_ID

    def get_failure_message(self, global_context):
        return messages.ACTION_SET_CUSTOMERS_EXTERNAL_ID_FAILED

    def filter_action(self, global_context):
        return (
                not is_copy_external_id_disabled(global_context)
                and super(SetCustomersExternalId, self).filter_action(global_context)
        )

    def is_critical(self):
        return False

    def _get_customer_failure_message(self, global_context, customer):
        return messages.ACTION_SET_CUSTOMERS_EXTERNAL_ID_CUSTOMER_FAILED.format(customer_username=customer.login)

    def _run_customer(self, global_context, customer, reseller_username=None):
        """Set External ID for given customer in target panel

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type customer: parallels.core.target_data_model.Client
        :type reseller_username: str | None
        """
        customer_dump = self._get_customer_dump(global_context, customer)
        if customer_dump is None:
            logger.error(messages.ACTION_SET_CUSTOMERS_EXTERNAL_ID_CUSTOMER_NOT_EXISTS_SOURCE.format(
                customer_username=customer.login
            ))
            return

        if customer_dump.external_id is None:
            logger.debug(messages.ACTION_SET_CUSTOMERS_EXTERNAL_ID_CUSTOMER_EMPTY.format(
                customer_username=customer.login
            ))
            return

        target_customer = global_context.hosting_repository.customer.get_by_username(customer.login)
        if target_customer is None:
            logger.warning(messages.ACTION_SET_CUSTOMERS_EXTERNAL_ID_CUSTOMER_NOT_EXISTS_TARGET.format(
                customer_username=customer.login
            ))
            return

        logger.info(messages.ACTION_SET_CUSTOMERS_EXTERNAL_ID_CUSTOMER.format(customer_username=customer.login))
        global_context.hosting_repository.customer.set_external_id(customer.login, customer_dump.external_id)

    @staticmethod
    def _get_customer_dump(global_context, customer):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type customer: parallels.core.target_data_model.Client
        :rtype: parallels.core.dump.data_model.Client | None
        """
        for source in global_context.get_primary_sources_info():
            for customer_dump in source.load_raw_dump().iter_all_clients():
                if customer.login == customer_dump.login:
                    return customer_dump
        return None
