from parallels.core.logging import get_logger
from parallels.plesk import messages

logger = get_logger(__name__)


def remove_coinciding_dns_records(global_context, subscription, domain_name):
    """Remove DNS records, which match given domain name

    :type global_context: parallels.core.global_context.GlobalMigrationContext
    :type subscription: parallels.core.migrated_subscription.MigratedSubscription
    :type domain_name: str
    """
    # retrieve DNS records coinciding with the domain name
    dns_records = []
    try:
        filter_domain_name = subscription.converted_dump.get_domain_names()
        dns_records = global_context.hosting_repository.dns_record.get_list(
            filter_domain_name=filter_domain_name,
            filter_name=['%s.' % domain_name]
        )
    except Exception:
        # unable to retrieve DNS records for some reason, so if such records actually exists,
        # they will not be removed and further creation of add-on domain will fail;
        # anyway, log an exception and go ahead
        logger.exception()

    if len(dns_records) < 1:
        return

    logger.info(messages.REMOVE_COINCIDING_DNS_RECORDS.format(
        subscription_name=subscription.name,
        domain_name=domain_name
    ))
    for dns_record in dns_records:
        try:
            logger.info(messages.REMOVE_COINCIDING_DNS_RECORDS_REMOVE.format(
                subscription_name=subscription.name,
                dns_record_domain_name=dns_record.domain_name,
                dns_record_pretty_name=dns_record.pretty_name
            ))
            global_context.hosting_repository.dns_record.remove(dns_record)
        except Exception as e:
            logger.exception()
            logger.fwarn(
                messages.REMOVE_COINCIDING_DNS_RECORDS_REMOVE_ERROR,
                subscription_name=subscription.name,
                domain_name=domain_name,
                dns_record_domain_name=dns_record.domain_name,
                dns_record_pretty_name=dns_record.pretty_name,
                reason=e
            )
