import dns.message, dns.query, dns.rdtypes.ANY.MX

from plesk_mail_migrator.providers.imap.server_detect.methods.base import ImapServerDetectMethod


class MxRecordValueImapServerDetectMethod(ImapServerDetectMethod):
    """Use MX record values as IMAP host"""

    def __init__(self, dns_server):
        """
        :param str | unicode dns_server: DNS server IP or hostname
        """
        self._dns_server = dns_server

    def detect(self, domain_name):
        """Detect IMAP host(s) for specified domain name.

        For example, if you have e-mail "john@example.com", and you pass "example.com" to this function,
        it may detect and return two IMAP servers ["imap1.example.com", "imap2.example.com"]

        :type domain_name: str | unicode
        :rtype: list[str | unicode]
        """
        dns_request = dns.message.make_query(domain_name, dns.rdatatype.MX, dns.rdataclass.IN)
        dns_response = dns.query.udp(dns_request, self._dns_server)
        result = [
            {
                'preference': rdata.preference,
                'exchange': rdata.exchange.to_text(True)
            }
            for rdset in dns_response.answer
            for rdata in rdset
        ]
        result.sort(key=lambda r: r['preference'], reverse=True)
        return [record['exchange'] for record in result]

    def is_fast(self):
        """Whether the method is fast: fast methods do not perform requests to thirdparty services (DNS, HTTP)

        :rtype: bool
        """
        return False


    def get_method_id(self):
        """Get method ID to be used in command line, statistics, etc

        :rtype: str | unicode
        """
        return 'mx-record-value'
