import { Dropdown } from "bootstrap";
import NoteContextAwareWidget from "./note_context_aware_widget.js";
import { getAvailableLocales, type Locale } from "../services/i18n.js";
import { t } from "i18next";
import type { EventData } from "../components/app_context.js";
import type FNote from "../entities/fnote.js";
import attributes from "../services/attributes.js";
const TPL = `\
    
         
    
`;
export default class NoteLanguageWidget extends NoteContextAwareWidget {
    private dropdown!: Dropdown;
    private $noteLanguageDropdown!: JQuery;
    private $noteLanguageButton!: JQuery;
    private $noteLanguageDesc!: JQuery;
    private locales: (Locale | "---")[];
    constructor() {
        super();
        this.locales = [
            {
                id: "",
                name: t("note_language.not_set")
            },
            "---",
            ...getAvailableLocales()
        ];
    }
    doRender() {
        this.$widget = $(TPL);
        this.dropdown = Dropdown.getOrCreateInstance(this.$widget.find("[data-bs-toggle='dropdown']")[0]);
        this.$widget.on("show.bs.dropdown", () => this.renderDropdown());
        this.$noteLanguageDropdown = this.$widget.find(".note-language-dropdown")
        this.$noteLanguageButton = this.$widget.find(".note-language-button");
        this.$noteLanguageDesc = this.$widget.find(".note-language-desc");
    }
    renderDropdown() {
        this.$noteLanguageDropdown.empty();
        if (!this.note) {
            return;
        }
        for (const locale of this.locales) {
            if (typeof locale === "object") {
                const $title = $("").text(locale.name);
                const $link = $('')
                    .attr("data-language", locale.id)
                    .append('✓  ')
                    .append($title)
                    .on("click", () => {
                        const languageId = $link.attr("data-language") ?? "";
                        this.save(languageId);
                    })
                this.$noteLanguageDropdown.append($link);
            } else {
                this.$noteLanguageDropdown.append('
');
            }
        }
    }
    async save(languageId: string) {
        if (!this.note) {
            return;
        }
        attributes.setAttribute(this.note, "label", "language", languageId);
    }
    async refreshWithNote(note: FNote) {
        const languageId = note.getLabelValue("language") ?? "";
        const language = this.locales.find((l) => (typeof l === "object" && l.id === languageId)) as Locale;
        this.$noteLanguageDesc.text(language.name);
    }
    async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
        if (loadResults.getAttributeRows().find((a) => a.noteId === this.noteId && a.name === "language")) {
            this.refresh();
        }
    }
}