from plesk_mail_migrator.providers.imap.server_detect.methods.base import ImapServerDetectMethod
from plesk_mail_migrator.providers.imap.server_detect.utils import get_parent_domain_chain, load_mozilla_database


class MozillaDatabaseImapServerDetectMethod(ImapServerDetectMethod):
    """Detect IMAP host by looking for it in Mozilla/Thunderbird database (stored in local file)"""

    def __init__(self):
        self._database = load_mozilla_database()

    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]
        """
        for checked_domain_name in get_parent_domain_chain(domain_name):
            if checked_domain_name in self._database:
                return self._database[checked_domain_name]

        return []

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

        :rtype: bool
        """
        return True

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

        :rtype: str | unicode
        """
        return 'mozilla-database'
