from parallels.core.logging import get_logger
from parallels.core.converter.business_objects.common import SOURCE_TARGET
from parallels.plesk import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.utils.common import if_not_none

logger = get_logger(__name__)


class DeployHostingPlans(CommonAction):
    def get_description(self):
        return messages.ACTION_CREATE_HOSTING_PLANS

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

    def run(self, global_context):
        """Create hosting plans in target Plesk

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        for plan in global_context.target_model.plans.values():
            self._create_plan(global_context, plan)
        for reseller in global_context.target_model.resellers.values():
            for plan in reseller.plans.values():
                self._create_plan(global_context, plan, reseller)

    @staticmethod
    def _create_plan(context, plan, reseller=None):
        """
        :type context: parallels.core.global_context.GlobalMigrationContext
        :type plan: parallels.core.target_data_model.Plan
        :type reseller: parallels.core.target_data_model.Reseller | None
        """
        plan_name = plan.name.strip()
        if plan.source == SOURCE_TARGET:
            if reseller is None:
                logger.debug(messages.ACTION_CREATE_HOSTING_PLANS_ADMIN_PLAN_EXISTS.format(
                    hosting_plan_name=plan_name
                ))
            else:
                logger.debug(messages.ACTION_CREATE_HOSTING_PLANS_RESELLER_PLAN_EXISTS.format(
                    hosting_plan_name=plan_name,
                    reseller_username=reseller.login
                ))
            return
        with context.safe.try_plan(
            if_not_none(reseller, lambda r: r.login),
            plan_name,
            messages.ACTION_CREATE_HOSTING_PLANS_PLAN_FAILED.format(hosting_plan_name=plan_name)
        ):
            if reseller is None:
                logger.info(messages.ACTION_CREATE_HOSTING_PLANS_CREATE_ADMIN_PLAN.format(
                    hosting_plan_name=plan_name
                ))
            else:
                logger.info(messages.ACTION_CREATE_HOSTING_PLANS_CREATE_RESELLER_PLAN.format(
                    hosting_plan_name=plan_name,
                    reseller_username=reseller.login
                ))
            owner_username = if_not_none(reseller, lambda r: r.login)
            if not plan.is_addon:
                context.hosting_repository.service_plan.create(plan_name, owner_username, plan.settings)
            else:
                context.hosting_repository.service_plan_addon.create(plan_name, owner_username, plan.settings)
