/*
THIS IS A GENERATED/BUNDLED FILE BY ROLLUP
if you want to view the source visit the plugins github repository
*/

'use strict';

var obsidian = require('obsidian');

/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

const DEFAULT_SETTINGS = {
    template: `{{text}}\n> [Wikipedia]({{url}})`,
    shouldUseParagraphTemplate: true,
    shouldBoldSearchTerm: true,
    paragraphTemplate: `> {{paragraphText}}\n>\n`,
    language: "en",
};
const extractApiUrl = "wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&redirects&origin=*&titles=";
const disambiguationIdentifier = "may refer to:";
class WikipediaPlugin extends obsidian.Plugin {
    getLanguage() {
        return this.settings.language ? this.settings.language : "en";
    }
    getUrl(title) {
        return `https://${this.getLanguage()}.wikipedia.org/wiki/${encodeURI(title)}`;
    }
    getApiUrl() {
        return `https://${this.getLanguage()}.` + extractApiUrl;
    }
    formatExtractText(extract, searchTerm) {
        const text = extract.text;
        let formattedText = "";
        if (this.settings.shouldUseParagraphTemplate) {
            const split = text.split("==")[0].trim().split("\n");
            formattedText = split
                .map((paragraph) => this.settings.paragraphTemplate.replace("{{paragraphText}}", paragraph))
                .join("")
                .trim();
        }
        else {
            formattedText = text.split("==")[0].trim();
        }
        if (this.settings.shouldBoldSearchTerm) {
            const pattern = new RegExp(searchTerm, "i");
            formattedText = formattedText.replace(pattern, `**${searchTerm}**`);
        }
        return formattedText;
    }
    handleNotFound(searchTerm) {
        new obsidian.Notice(`${searchTerm} not found on Wikipedia.`);
    }
    handleCouldntResolveDisambiguation() {
        new obsidian.Notice(`Could not automatically resolve disambiguation.`);
    }
    hasDisambiguation(extract) {
        if (extract.text.includes(disambiguationIdentifier)) {
            return true;
        }
        return false;
    }
    parseResponse(json) {
        const pages = json.query.pages;
        const pageKeys = Object.keys(pages);
        if (pageKeys.includes("-1")) {
            return undefined;
        }
        const extracts = pageKeys.map((key) => {
            const page = pages[key];
            const extract = {
                title: page.title,
                text: page.extract,
                url: this.getUrl(page.title),
            };
            return extract;
        });
        return extracts[0];
    }
    formatExtractInsert(extract, searchTerm) {
        const formattedText = this.formatExtractText(extract, searchTerm);
        const template = this.settings.template;
        const formattedTemplate = template
            .replace("{{text}}", formattedText)
            .replace("{{searchTerm}}", searchTerm)
            .replace("{{url}}", extract.url);
        return formattedTemplate;
    }
    getWikipediaText(title) {
        return __awaiter(this, void 0, void 0, function* () {
            const url = this.getApiUrl() + encodeURIComponent(title);
            const requestParam = {
                url: url,
            };
            const resp = yield obsidian.request(requestParam)
                .then((r) => JSON.parse(r))
                .catch(() => new obsidian.Notice("Failed to get Wikipedia. Check your internet connection or language prefix."));
            const extract = this.parseResponse(resp);
            return extract;
        });
    }
    pasteIntoEditor(editor, searchTerm) {
        return __awaiter(this, void 0, void 0, function* () {
            let extract = yield this.getWikipediaText(searchTerm);
            if (!extract) {
                this.handleNotFound(searchTerm);
                return;
            }
            if (this.hasDisambiguation(extract)) {
                new obsidian.Notice(`Disambiguation found for ${searchTerm}. Choosing first result.`);
                const newSearchTerm = extract.text
                    .split(disambiguationIdentifier)[1]
                    .trim()
                    .split(",")[0]
                    .split("==")
                    .pop()
                    .trim();
                extract = yield this.getWikipediaText(newSearchTerm);
                if (!extract) {
                    this.handleCouldntResolveDisambiguation();
                    return;
                }
            }
            editor.replaceSelection(this.formatExtractInsert(extract, searchTerm));
        });
    }
    getWikipediaTextForActiveFile(editor) {
        return __awaiter(this, void 0, void 0, function* () {
            const activeFile = yield this.app.workspace.getActiveFile();
            if (activeFile) {
                const searchTerm = activeFile.basename;
                if (searchTerm) {
                    yield this.pasteIntoEditor(editor, searchTerm);
                }
            }
        });
    }
    getWikipediaTextForSearchTerm(editor) {
        return __awaiter(this, void 0, void 0, function* () {
            new WikipediaSearchModal(this.app, this, editor).open();
        });
    }
    onload() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.loadSettings();
            this.addCommand({
                id: "wikipedia-get-active-note-title",
                name: "Get Wikipedia for Active Note Title",
                editorCallback: (editor) => this.getWikipediaTextForActiveFile(editor),
            });
            this.addCommand({
                id: "wikipedia-get-search-term",
                name: "Get Wikipedia for Search Term",
                editorCallback: (editor) => this.getWikipediaTextForSearchTerm(editor),
            });
            this.addSettingTab(new WikipediaSettingTab(this.app, this));
        });
    }
    loadSettings() {
        return __awaiter(this, void 0, void 0, function* () {
            this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
        });
    }
    saveSettings() {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.saveData(this.settings);
        });
    }
}
class WikipediaSearchModal extends obsidian.Modal {
    constructor(app, plugin, editor) {
        super(app);
        this.plugin = plugin;
        this.editor = editor;
    }
    onOpen() {
        let { contentEl } = this;
        contentEl.createEl("h2", { text: "Enter Search Term:" });
        const inputs = contentEl.createDiv("inputs");
        const searchInput = new obsidian.TextComponent(inputs).onChange((searchTerm) => {
            this.searchTerm = searchTerm;
        });
        searchInput.inputEl.focus();
        searchInput.inputEl.addEventListener("keydown", (event) => {
            if (event.key === "Enter") {
                this.close();
            }
        });
        const controls = contentEl.createDiv("controls");
        const searchButton = controls.createEl("button", {
            text: "Search",
            cls: "mod-cta",
            attr: {
                autofocus: true,
            },
        });
        searchButton.addEventListener("click", this.close.bind(this));
        const cancelButton = controls.createEl("button", { text: "Cancel" });
        cancelButton.addEventListener("click", this.close.bind(this));
    }
    onClose() {
        return __awaiter(this, void 0, void 0, function* () {
            let { contentEl } = this;
            contentEl.empty();
            if (this.searchTerm) {
                yield this.plugin.pasteIntoEditor(this.editor, this.searchTerm);
            }
        });
    }
}
class WikipediaSettingTab extends obsidian.PluginSettingTab {
    constructor(app, plugin) {
        super(app, plugin);
        this.plugin = plugin;
    }
    display() {
        let { containerEl } = this;
        containerEl.empty();
        containerEl.createEl("h2", { text: "Obsidian Wikipedia" });
        new obsidian.Setting(containerEl)
            .setName("Wikipedia Language Prefix")
            .setDesc(`Choose Wikipedia language prefix to use (ex. en for English)`)
            .addText((textField) => {
            textField
                .setValue(this.plugin.settings.language)
                .onChange((value) => __awaiter(this, void 0, void 0, function* () {
                this.plugin.settings.language = value;
                yield this.plugin.saveSettings();
            }));
        });
        new obsidian.Setting(containerEl)
            .setName("Wikipedia Extract Template")
            .setDesc(`Set markdown template for extract to be inserted.\n
        Available template variables are {{text}}, {{searchTerm}} and {{url}}.
        `)
            .addTextArea((textarea) => textarea
            .setValue(this.plugin.settings.template)
            .onChange((value) => __awaiter(this, void 0, void 0, function* () {
            this.plugin.settings.template = value;
            yield this.plugin.saveSettings();
        })));
        new obsidian.Setting(containerEl)
            .setName("Bold Search Term?")
            .setDesc("If set to true, the first instance of the search term will be **bolded**")
            .addToggle((toggle) => toggle
            .setValue(this.plugin.settings.shouldBoldSearchTerm)
            .onChange((value) => __awaiter(this, void 0, void 0, function* () {
            this.plugin.settings.shouldBoldSearchTerm = value;
            yield this.plugin.saveSettings();
        })));
        new obsidian.Setting(containerEl)
            .setName("Use paragraph template?")
            .setDesc("If set to true, the paragraph template will be inserted for each paragraph of text for {{text}} in main template.")
            .addToggle((toggle) => toggle
            .setValue(this.plugin.settings.shouldUseParagraphTemplate)
            .onChange((value) => __awaiter(this, void 0, void 0, function* () {
            this.plugin.settings.shouldUseParagraphTemplate = value;
            yield this.plugin.saveSettings();
        })));
        new obsidian.Setting(containerEl)
            .setName("Paragraph Template")
            .setDesc(`Set markdown template for extract paragraphs to be inserted.\n
        Available template variables are: {{paragraphText}}
        `)
            .addTextArea((textarea) => textarea
            .setValue(this.plugin.settings.paragraphTemplate)
            .onChange((value) => __awaiter(this, void 0, void 0, function* () {
            this.plugin.settings.paragraphTemplate = value;
            yield this.plugin.saveSettings();
        })));
    }
}

module.exports = WikipediaPlugin;
//# sourceMappingURL=data:application/json;charset=utf-8;base64, 
