from parallels.core.logging import get_logger
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.plesk import messages
from parallels.plesk.actions.hosting_settings.utils import is_copy_external_id_disabled

logger = get_logger(__name__)


class SetSubscriptionExternalId(SubscriptionAction):
    def get_description(self):
        return messages.ACTION_SET_SUBSCRIPTION_EXTERNAL_ID

    def is_critical(self):
        return False

    def filter_subscription(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return not is_copy_external_id_disabled(global_context) and subscription.raw_dump.external_id is not None

    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_SET_SUBSCRIPTION_EXTERNAL_ID_FAILED.format(subscription_name=subscription.name)

    def run(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        if subscription.raw_dump.external_id is None:
            logger.debug(messages.ACTION_SET_SUBSCRIPTION_EXTERNAL_ID_EMPTY.format(
                subscription_name=subscription.name
            ))
            return

        target_subscription = global_context.hosting_repository.subscription.get_by_name(subscription.name)
        if target_subscription is None:
            logger.warning(messages.ACTION_SET_SUBSCRIPTION_EXTERNAL_ID_NOT_EXISTS.format(
                subscription_name=subscription.name
            ))
            return

        global_context.hosting_repository.subscription.set_external_id(
            subscription.name,
            subscription.raw_dump.external_id
        )
