/*
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 = {
    termsAccepted: false,
    isPremium: false
};
const BASE_URL = "https://ocr.taskbone.com";
const privacyPolicyURL = "https://www.taskbone.com/legal/privacy";
const contactURL = "http://www.taskbone.com/contact";
class TaskboneOCRPlugin extends obsidian.Plugin {
    onload() {
        return __awaiter(this, void 0, void 0, function* () {
            console.log('Taskbone OCR: start loading plugin');
            yield this.loadSettings();
            this.addSettingTab(new TaskboneOCRSettingTab(this.app, this));
            this.addCommand({
                id: 'open-image-select-modal',
                name: 'Create annotation page for image',
                callback: () => __awaiter(this, void 0, void 0, function* () {
                    if (!this.settings.termsAccepted) {
                        const errorText = `Please go to the Taskbone OCR plugin settings and accept the privacy policy.`;
                        return new ErrorModal(this.app, errorText).open();
                    }
                    if (!this.settings.isPremium) {
                        if (!this.settings.standardToken) {
                            const tokenResponse = yield fetch(BASE_URL + '/get-new-token', {
                                method: 'post'
                            });
                            if (tokenResponse.status == 200) {
                                const jsonResponse = yield tokenResponse.json();
                                this.settings.standardToken = jsonResponse.token;
                                this.saveSettings();
                            }
                            else {
                                const errorText = `Taskbone OCR Error: ${tokenResponse.status}<br/>Please try again later.`;
                                return new ErrorModal(this.app, errorText).open();
                            }
                        }
                    }
                    else {
                        if (!this.settings.premiumToken) {
                            const errorText = `Your plugin configuration is incomplete. Check the plugin settings and either enter a token or disable the 'I have a personal token' setting.`;
                            return new ErrorModal(this.app, errorText).open();
                        }
                    }
                    const images = this.getNotAnnotatedImagePaths();
                    if (images.length > 0) {
                        new FileSelectorModal(this.app, this).open();
                    }
                    else {
                        new ErrorModal(this.app, "All supported image files already have an annotation file.").open();
                    }
                })
            });
        });
    }
    onunload() {
        console.log('Taskbone OCR: unloading plugin');
    }
    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);
        });
    }
    getTextForFile(path) {
        return __awaiter(this, void 0, void 0, function* () {
            const vault = this.app.vault;
            const file = vault.getFiles().filter((file) => {
                return file.path == path;
            })[0];
            const fileBuffer = yield this.app.vault.readBinary(file);
            const formData = new FormData();
            formData.append('image', new Blob([fileBuffer]));
            const token = this.settings.isPremium ? this.settings.premiumToken : this.settings.standardToken;
            try {
                const response = yield fetch(BASE_URL + '/get-text', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    },
                    method: "post",
                    body: formData
                });
                if (response.status == 200) {
                    const jsonResponse = yield response.json();
                    const text = jsonResponse === null || jsonResponse === void 0 ? void 0 : jsonResponse.text;
                    return text || '';
                }
                else {
                    const errorText = `Could not read Text from ${path}:<br/> Error: ${response.status}`;
                    new ErrorModal(this.app, errorText).open();
                }
            }
            catch (error) {
                const errorText = `The OCR service seems unavailable right now. Please try again later.`;
                new ErrorModal(this.app, errorText).open();
            }
        });
    }
    createAnnotationFileForFile(path) {
        return __awaiter(this, void 0, void 0, function* () {
            const imageText = yield this.getTextForFile(path);
            if (!imageText)
                return;
            if (imageText.length == 0) {
                new ErrorModal(this.app, `No text found in ${path}`).open();
            }
            else {
                const annotationFileContent = `![[${path}]]\n\n${imageText}`;
                const annotationFilePath = path + '.annotations.md';
                this.app.vault.create(annotationFilePath, annotationFileContent);
            }
        });
    }
    getNotAnnotatedImagePaths() {
        const files = this.app.vault.getFiles();
        const markdownFilePaths = this.app.vault.getMarkdownFiles().map((file) => {
            return file.path;
        });
        const images = files.filter((file) => {
            const isImage = ['png', 'jpg', 'jpeg'].includes(file.extension);
            if (!isImage)
                return false;
            const annotationFilePath = file.path + '.annotations.md';
            const annotationFileAlreadyExist = markdownFilePaths.contains(annotationFilePath);
            return !annotationFileAlreadyExist;
        });
        const imagePaths = images.map((file) => {
            return file.path;
        });
        return imagePaths;
    }
}
class FileSelectorModal extends obsidian.SuggestModal {
    constructor(app, plugin) {
        super(app);
        this.app = app;
        this.plugin = plugin;
    }
    getSuggestions(query) {
        const imagePaths = this.plugin.getNotAnnotatedImagePaths();
        if (query.length == 0) {
            return imagePaths;
        }
        const filteredImageNames = imagePaths.filter((path, index, paths) => {
            path.contains(query);
            return path.contains(query);
        });
        return filteredImageNames;
    }
    renderSuggestion(value, el) {
        el.setText(value);
    }
    onChooseSuggestion(item, evt) {
        return __awaiter(this, void 0, void 0, function* () {
            this.plugin.createAnnotationFileForFile(item);
        });
    }
}
class ErrorModal extends obsidian.Modal {
    constructor(app, message) {
        super(app);
        this.message = message;
    }
    onOpen() {
        this.titleEl.setText("Taskbone OCR Error");
        this.contentEl.innerHTML = this.message;
    }
    onClose() {
        this.containerEl.empty();
    }
}
class TaskboneOCRSettingTab extends obsidian.PluginSettingTab {
    constructor(app, plugin) {
        super(app, plugin);
        this.plugin = plugin;
    }
    display() {
        let { containerEl } = this;
        containerEl.empty();
        containerEl.createEl('h2', { text: 'Taskbone OCR Settings' });
        containerEl.createEl('p', { text: 'The Taskbone OCR service is provided for free (within reasonable limits).' });
        const div = containerEl.createEl('div');
        const premiumText = document.createElement('p');
        premiumText.innerHTML = `<a href="${contactURL}">Get in touch</a> if you think you are outside of these limits or if you are interested in any of the following features:<ul><li>PDF support</li><li>bigger file size limit</li><li>bulk operations (e.g. process a whole directory with lots of images)</li><li>General image annotations (find relevant tags for images)</li></ul>`;
        div.appendChild(premiumText);
        const acceptTermsSetting = new obsidian.Setting(containerEl)
            .setName('Accept Privacy Policy and Terms and Conditions')
            .addToggle((toggle) => toggle
            .setValue(this.plugin.settings.termsAccepted)
            .onChange((value) => {
            this.plugin.settings.termsAccepted = value;
            this.plugin.saveData(this.plugin.settings);
            this.display();
        }));
        acceptTermsSetting.descEl.innerHTML = `I accept the Taskbone <a href="${privacyPolicyURL}">Privacy Policy</a>`;
        new obsidian.Setting(containerEl)
            .setName('I have a personal token')
            .setDesc('Switch on, if you received a custom authentication token')
            .addToggle((toggle) => toggle
            .setValue(this.plugin.settings.isPremium)
            .onChange((value) => {
            this.plugin.settings.isPremium = value;
            this.plugin.saveData(this.plugin.settings);
            this.display();
        }));
        if (this.plugin.settings.isPremium) {
            new obsidian.Setting(containerEl)
                .setName('Authentication Token')
                .setDesc('Copy and paste the token you received from taskbone')
                .addText(text => text
                .setPlaceholder('Enter your token')
                .setValue(this.plugin.settings.premiumToken)
                .onChange((value) => __awaiter(this, void 0, void 0, function* () {
                this.plugin.settings.premiumToken = value;
                yield this.plugin.saveSettings();
            })));
        }
    }
}

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