from parallels.core import messages
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.actions.utils.logging_properties \
    import LoggingProperties
from parallels.core.reports.model.issue import Issue


class CheckServicePlanAccordance(SubscriptionBackupAction):
    def get_description(self):
        return messages.ACTION_CHECK_SERVICE_PLAN_ACCORDANCE_DESCRIPTION

    def get_failure_message(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return messages.ACTION_CHECK_SERVICE_PLAN_ACCORDANCE_FAILURE % subscription.name

    def is_critical(self):
        """If action is critical or not

        If action is critical and it failed for a subscription, migration tool
        won't run the next operations for the subscription.

        :rtype: bool
        """
        return False

    def get_logging_properties(self):
        return LoggingProperties(info_log=False)

    def _run_subscription_backup(self, global_context, subscription, subscription_backup):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :type subscription_backup: parallels.core.dump.data_model.Subscription
        """

        is_custom = subscription.model.plan_name is None
        is_locked = subscription.raw_dump.locked
        if is_custom or is_locked:
            return

        service_plan = global_context.hosting_repository.service_plan.get_by_name(
            subscription.model.plan_name,
            None if subscription.model_reseller is None else subscription.model_reseller.login
        )

        if (
            subscription_backup.get_phosting_sysuser_name() is not None and
            subscription.raw_dump.plan is not None and
            subscription.raw_dump.plan.properties.get('shell', '/bin/false') != '/bin/false' and
            service_plan is not None and service_plan.shell == '/bin/false'
        ):
            subscription.add_report_issue(
                global_context.pre_check_report,
                'service-plan-accordance-issue', Issue.SEVERITY_WARNING,
                messages.SERVICE_PLAN_ACCORDANCE_ISSUE.format(
                    subscription_name=subscription.name,
                    plan_name=subscription.model.plan_name
                ),
                messages.SERVICE_PLAN_ACCORDANCE_SOLUTION.format(
                    subscription_name=subscription.name,
                    plan_name=subscription.model.plan_name
                )
            )
