from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.utils.multithreading_properties import MultithreadingProperties
from parallels.core.utils.migrator_utils import get_optional_option_value

logger = get_logger(__name__)


class CopyDatabaseContent(SubscriptionAction):
    def get_description(self):
        return messages.ACTION_COPY_DATABASE_CONTENT

    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.FAILED_COPY_DATABASE_CONTENT_OF_SUBSCRIPTION

    def filter_subscription(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """

        source_server = subscription.web_source_server
        if source_server is None:
            return False

        db_content_transfer_option = source_server.settings().config_section.get('copy-db-content', 'full')
        config_skip_copy_db_content = db_content_transfer_option != 'full'
        cli_skip_copy_db_content = get_optional_option_value(
            global_context.options, 'skip_copy_db_content', False
        )

        if config_skip_copy_db_content or cli_skip_copy_db_content:
            logger.info(
                messages.LOG_NO_NEED_TO_COPY_DB_CONTENT_BECAUSE_DISABLED_BY_USER,
                subscription.name
            )
            return False
        else:
            return True

    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_multithreading_properties(self):
        """Get how multithreading should be applied for that action

        :rtype: parallels.core.actions.utils.multithreading_properties.MultithreadingProperties
        """
        return MultithreadingProperties(can_use_threads=True, use_threads_by_default=True)

    def run(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        global_context.migrator.transfer_subscription_databases(subscription)
