import sys

from parallels.core import MigrationNoContextError
from parallels.core.logging import get_logger
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.actions.base.common_action import CommonAction
from parallels.plesk import messages

logger = get_logger(__name__)


class CheckVersions(CommonAction):
    """Check that source Plesk version is lower that target Plesk version

    We don't support migration to lower version of Plesk, so we should immediately stop migration and
    inform customer about the issue.
    """

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

        :rtype: str
        """
        return messages.ACTION_CHECK_PLESKS_VERSIONS_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_CHECK_PLESKS_VERSIONS_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(compound=False)

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: None
        """
        if sys.version_info.major >= 3:
            str_type = str
        else:
            str_type = unicode
        target_version = global_context.conn.target.plesk_server.get_plesk_version()
        for source_id in global_context.conn.get_source_plesks().keys():
            source_server = global_context.conn.get_source_node(source_id)
            source_version = source_server.get_plesk_version()
            if target_version < source_version:
                raise MigrationNoContextError(messages.FAILURE_TARGET_VERSION_IS_LOWER.format(
                    source_version=".".join([str_type(i) for i in source_version]),
                    target_version=".".join([str_type(i) for i in target_version]),
                    source_id=source_id
                ))
