# SPDX-FileCopyrightText: 2013-2023 Blender Authors
#
# SPDX-License-Identifier: GPL-2.0-or-later

# Update "languages" text file used by Blender at runtime to build translations menu.


OK = 0
MISSING = 1
TOOLOW = 2
SKIPPED = 3
FLAG_MESSAGES = {
    OK: "",
    MISSING: "No translation yet.",
    TOOLOW: "Not complete enough to be included.",
    SKIPPED: "Skipped (see IMPORT_LANGUAGES_SKIP in settings.py).",
}


def gen_menu_file(stats, settings):
    # Generate languages file content used by Blender's i18n system.
    # First, match all entries in LANGUAGES to a `lang` in stats, if possible!
    # Returns a iterable of text lines.
    tmp = []
    for uid_num, label, uid in settings.LANGUAGES:
        if uid in stats:
            if uid in settings.IMPORT_LANGUAGES_SKIP:
                tmp.append((stats[uid], uid_num, label, uid, SKIPPED))
            else:
                tmp.append((stats[uid], uid_num, label, uid, OK))
        else:
            tmp.append((0.0, uid_num, label, uid, MISSING))
    stats = tmp
    stats = sorted(stats, key=lambda it: it[0], reverse=True)
    langs = []
    highest_uid = 0
    for lvl, uid_num, label, uid, flag in stats:
        if lvl < settings.IMPORT_MIN_LEVEL and flag == OK:
            flag = TOOLOW
        if uid_num == 0:
            # Insert default language (Automatic) at index 0, after sorting.
            default_lang = (uid_num, label, uid, flag, lvl)
            continue
        langs.append((uid_num, label, uid, flag, lvl))
        if abs(uid_num) > highest_uid:
            highest_uid = abs(uid_num)
    # Sort languages by name.
    langs.sort(key=lambda it: it[1])
    langs.insert(0, default_lang)
    data_lines = [
        "# File used by Blender to know which languages (translations) are available, ",
        "# and to generate translation menu.",
        "#",
        "# File format:",
        "# ID:MENULABEL:ISOCODE",
        "# ID must be unique, except for 0 value (marks categories for menu).",
        "# Line starting with a # are comments!",
        "#",
        "# Automatically generated by _bl_i18n_utils/utils_languages_menu.py script.",
        "# Highest ID currently in use: {}".format(highest_uid),
    ]
    for uid_num, label, uid, flag, lvl in langs:
        if flag == OK:
            data_lines.append("{}:{}:{}:{}%".format(uid_num, label, uid, round(lvl * 100)))
        else:
            # Non-existing, commented entry!
            data_lines.append("# {} #{}:{}:{}:{}%".format(FLAG_MESSAGES[flag], uid_num, label, uid, round(lvl * 100)))
    return data_lines
