from parallels.core.logging import get_logger
from parallels.plesk.source.plesk import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.utils.common import between_inclusive
from parallels.core.utils.yaml_utils import read_yaml


logger = get_logger(__name__)


class MergeApplications(CommonAction):
    def get_description(self):
        return messages.ACTION_MERGE_APPLICATIONS_DESCRIPTION

    def get_failure_message(self, global_context):
        """
        :type global_context: parallels.plesk.source.plesk.global_context.PleskGlobalMigrationContext
        """
        return messages.ACTION_MERGE_APPLICATIONS_FAILURE

    def get_logging_properties(self):
        return LoggingProperties(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):
        """
        :type global_context: parallels.plesk.source.plesk.global_context.PleskGlobalMigrationContext
        """
        for source_id, settings in global_context.conn.get_source_plesks().items():
            source_server = global_context.conn.get_source_node(source_id)
            if source_server.is_windows() and between_inclusive(source_server.plesk_version, (10, 3), (11, 1)):
                applications_str = read_yaml(
                    global_context.session_files.get_path_to_applications_filename(source_id)
                )

                backup = global_context.load_raw_dump(settings)
                backup.replace_applications(applications_str)
                backup.save_to_the_same_file()
