from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.logging import get_logger
from parallels.plesk.source.web import messages
from parallels.plesk.source.web.actions.base.site_migration import SiteMigrationAction
from parallels.plesk.source.web.utils.status_storage import StatusStorage
from parallels.plesk.source.web.utils.status_utils import set_status_for_all_migration_list_objects

logger = get_logger(__name__)


class StartMigration(SiteMigrationAction):
    """Start migration - acquire per-session lock and initialize statuses of migrated objects"""

    def get_description(self):
        """Get short description of action as string

        :rtype: str | unicode
        """
        return messages.ACTION_START_MIGRATION_DESCRIPTION

    def get_failure_message(self, global_context):
        """Get message for situation when action failed

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: str | unicode
        """
        return messages.ACTION_START_MIGRATION_FAILURE

    def get_logging_properties(self):
        """Get how action should be logged to migration tools end-user

        :rtype: parallels.core.actions.utils.logging_properties.LoggingProperties
        """
        return LoggingProperties(info_log=False, compound=False)

    def run(self, global_context):
        """Run action

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :rtype: None
        """
        # Set all selected objects as queued - till we actually start the migration.
        set_status_for_all_migration_list_objects(
            global_context.site_migration_list, global_context.status_storage, StatusStorage.STATUS_QUEUED
        )

        # Acquire per-session migration lock to avoid multiple migrations running in parallel.
        # The next process will wait till the previous ones finishes.
        global_context.site_migration_lock.acquire_block()

        # Reset status for connect/scan content operations
        global_context.status_storage.reset_operations_status()

        # Set all selected objects as in progress - as we acquired the lock and actually start the migration.
        set_status_for_all_migration_list_objects(
            global_context.site_migration_list, global_context.status_storage, StatusStorage.STATUS_IN_PROGRESS
        )
