# Due to a bug in pycountry 22.3.5 that prevents packaging using py2exe on
# windows, we had to replace it with this. It was written to be a
# drop-in replacement so at any point it should be possible to just remove it
# and import the original pycountry instead
from . import pycountry_mimick as pycountry


class ISO639:
    """
    Tiny utility class wrapper around pycountry, providing generic get
    functions that can work with any language code (2 or 3 digits versions)
    or language name.
    """

    @classmethod
    def get_by_code(cls_, language_code: str):
        """
        Attempts to get a pycountry.Language from a representation
        that may be alpha2 or alpha3

        Has to work around the fact that get is not case sensitive. A
        non-valid string could match. I.e. if you pass the alpha-2
        code 'en', it will match the language with name 'En', which is
        totally different.

        Returns None if the language code is not found in the db
        as well as if the string has lenght different from 2 or 3
        """
        if len(language_code) == 2:
            retval = pycountry.languages.get(alpha_2=language_code)
            if retval and language_code == retval.alpha_2:
                return retval
        elif len(language_code) == 3:
            retval = pycountry.languages.get(alpha_3=language_code)
            if retval and language_code == retval.alpha_3:
                return retval

        return None

    @classmethod
    def get_by_name(cls_, language_name: str):
        """
        Attempts to get a pycountry.Language from a string intepreted as
        language name.

        Has to work around the fact that get is not case sensitive. A
        non-valid name string could match. I.e. if you pass the alpha-2
        code 'en', it will match the language with name 'En', which is
        totally different.

        Returns None if the language is not found in the db
        """
        retval = pycountry.languages.get(name=language_name)
        # Check case sensitivity
        if retval and language_name == retval.name:
            return retval

        return None

    @classmethod
    def get_by_any(cls_, language_string: str):
        # Attempt to search by name first
        return (
            cls_.get_by_name(language_string) or
            cls_.get_by_code(language_string)
        )
