from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.customer_action import CustomerAction
from parallels.core.reports.model.issue import Issue
from parallels.core.target_data_model import CreatedClient

logger = get_logger(__name__)


class DeployCustomers(CustomerAction):
    def get_description(self):
        return messages.CREATE_CLIENTS_IN_TARGET_PANEL

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

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

    def _run_customer(self, global_context, customer, reseller_username=None):
        """Create 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
        """
        if customer.login not in global_context.target_existing_objects.customers:
            if reseller_username is None:
                logger.info(messages.CREATE_CLIENT_S_OWNED_BY_ADMINISTRATOR, customer.login)
            else:
                logger.info(messages.CREATE_CLIENT_S_OWNED_BY_RESELLER, customer.login, reseller_username)

            # invalidate cache associated with this customer
            global_context.cache_state_controllers.customer.invalidate_cache_states(customer.login)

            client_id, warnings = global_context.hosting_repository.customer.create(reseller_username, customer)
            for warning in warnings:
                global_context.safe.fail_client(
                    reseller_username, customer.login, warning,
                    is_critical=False,
                    severity=Issue.SEVERITY_WARNING
                )

            target_client = CreatedClient(id=client_id)
            global_context.target_existing_objects.customers[customer.login] = target_client
            customer.target_client = target_client
        else:
            logger.debug(messages.CLIENT_LOGIN_S_ALREADY_EXISTS_SKIP, customer.login)
