"""
This package handles ISO639-3 language codes.

The data comes from the tabular data made available from the
managing organization https://iso639-3.sil.org/code_tables/download_tables
which is turned into json and stored in a python file as a JSON string.

You can update the JSON by downloading a new data set and running the
"iso639_tab_to_py.py" script in this folder.

This was written to work like pycountry, for the scope required in the
ISO639 class from manifest_edit utility package. It should be a direct
one-to-one replacement.
"""
import os
import json
from collections import OrderedDict
from manifest_edit.context import Context
from .iso639_3_20220311 import LANGUAGES

JSON_STORE = "iso639_3_20220311.py"


class Language(OrderedDict):
    def __init__(self, *arg, **kw):
        super(Language, self).__init__(*arg, **kw)

    @property
    def name(self):
        return self.get("name", None)

    @property
    def alpha_2(self):
        retval = self.get("alpha_2")
        if retval:
            return retval
        else:
            raise AttributeError

    @property
    def alpha_3(self):
        return self.get("alpha_3", None)


class Languages:
    def load_from_json(self):
        languages_raw = json.loads(LANGUAGES)
        languages = [Language(lang) for lang in languages_raw]
        retval = (
            languages,
            {lang["alpha_3"]: lang for lang in languages},  # by alpha-3
            {
                lang["alpha_2"]: lang for lang in languages
            },  # by alpha-2, empty values will collapse to one
            {lang["name"]: lang for lang in languages},  # by name
        )

        return retval

    def __init__(self):
        this_dir, this_filename = os.path.split(__file__)  # Get path
        self.JSON_STORE_path = os.path.join(this_dir, JSON_STORE)
        try:
            (
                self.languages,
                self.languages_by_alpha3,
                self.languages_by_alpha2,
                self.languages_by_name,
            ) = self.load_from_json()
        except Exception as e_json:
            Context.log_warning(
                f"Cannot load ISO_LANGUAGES_CSV_STORE: exception {e_json}"
            )
            raise e_json
        else:
            Context.log_debug("Successfully loaded ISO_LANGUAGES_CSV_STORE!")

    def get(self, alpha_2=None, alpha_3=None, name=None):
        if alpha_2:
            return self.languages_by_alpha2.get(alpha_2, None)
        elif alpha_3:
            return self.languages_by_alpha3.get(alpha_3, None)
        elif name:
            return self.languages_by_name.get(name, None)
        else:
            Context.log_warning(
                "You must provide at least one among alpha_2, alpha_3 or name"
            )
            return None

    def __iter__(self):
        return iter(self.languages)


languages = Languages()
