from parallels.core import get_logger
from parallels.core.actions.utils.logging_properties import LoggingProperties
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 StartCheckApps(SiteMigrationAction):
    """Start check apps - acquire per-session lock and initialize statuses of objects to check"""

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

        :rtype: str | unicode
        """
        return messages.ACTION_START_CHECK_APPS_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_CHECK_APPS_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 get_storage_status_type(self):
        """Category for status in status storage

        :rtype: str | unicode
        """
        return StatusStorage.STORAGE_STATUS_TYPE_CHECK_STATUS

    def get_storage_issue_type(self):
        """Category for issues in status storage

        :rtype: str | unicode
        """
        return StatusStorage.STORAGE_ISSUES_TYPE_CHECK_ISSUES

    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 check.
        set_status_for_all_migration_list_objects(
            global_context.site_migration_list, global_context.status_storage, StatusStorage.STATUS_QUEUED,
            self.get_storage_status_type()
        )

        # 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()

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