from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.reseller_action import ResellerAction
from parallels.core.reports.model.issue import Issue

logger = get_logger(__name__)


class DeployResellers(ResellerAction):
    def get_description(self):
        return messages.ACTION_DEPLOY_RESELLERS

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

    def _get_reseller_failure_message(self, global_context, reseller):
        return messages.ACTION_DEPLOY_RESELLERS_RESELLER_FAILED.format(
            reseller_username=reseller.login
        )

    def _run_reseller(self, global_context, reseller):
        """Create given reseller in target panel

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type reseller: parallels.core.target_data_model.Reseller
        """
        if reseller.login in global_context.target_existing_objects.resellers:
            logger.debug(messages.ACTION_DEPLOY_RESELLERS_RESELLER_EXISTS.format(
                reseller_username=reseller.login
            ))
            return

        logger.info(messages.ACTION_DEPLOY_RESELLERS_RESELLER_CREATE.format(
            reseller_username=reseller.login
        ))

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

        _, warnings = global_context.hosting_repository.reseller.create(reseller)
        for warning in warnings:
            global_context.safe.fail_reseller(
                reseller.login, warning,
                is_critical=False,
                severity=Issue.SEVERITY_WARNING
            )
