from parallels.core import messages, safe_format, get_logger
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.converter import dns as dns_converter


logger = get_logger(__name__)


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

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

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

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return safe_format(messages.ACTION_CONVERT_DNS_RECORDS_FAILURE, subscription=subscription.name)

    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)

    def run(self, global_context, subscription):
        """Make subscription DNS records resolve to target server IP.

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        target_plesk_version = global_context.conn.target.plesk_server.plesk_version

        target_dns_template = global_context.hosting_repository.panel.get_dns_template(subscription.name)
        srv_dns_records_with_dot = target_plesk_version[:2] > (17, 8)
        dns_converter.replace_dns_record_ips(subscription, target_dns_template, srv_dns_records_with_dot)

        if target_plesk_version[:2] <= (17, 5):
            dns_converter.remove_caa_dns_records(subscription)
