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_utils import get_status_value

logger = get_logger(__name__)


class FinishMigration(SiteMigrationAction):
    """Finish migration - set finish statuses for all migrated objects"""

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

        :rtype: str | unicode
        """
        return messages.ACTION_FINISH_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_FINISH_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 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 run(self, global_context):
        """Run action

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :rtype: None
        """
        for application in global_context.list_migrated_applications():
            status = get_status_value(
                global_context, global_context.site_objects_safe.get_application(application)
            )

            global_context.status_storage.set_application_status(
                application.application_model.name, application.source_path, application.target_path, status
            )

        for folder in global_context.list_independent_migrated_folders():
            status = get_status_value(
                global_context, global_context.site_objects_safe.get_folder(folder)
            )

            global_context.status_storage.set_files_status(
                folder.source_absolute_path, folder.target_relative_path, status
            )

        for database in global_context.list_independent_migrated_databases():
            status = get_status_value(
                global_context, global_context.site_objects_safe.get_database(database)
            )

            global_context.status_storage.set_database_status(
                database.source_name, database.source_host, database.source_port,
                database.database_user.source_username, database.database_user.source_password, status
            )
