import TabAwareWidget from "./tab_aware_widget.js";
import noteAutocompleteService from "../services/note_autocomplete.js";
import server from "../services/server.js";
import contextMenuService from "../services/context_menu.js";
import attributesParser from "../services/attribute_parser.js";
import libraryLoader from "../services/library_loader.js";
import treeCache from "../services/tree_cache.js";
import attributeRenderer from "../services/attribute_renderer.js";
const HELP_TEXT = `
To add label, just type e.g. #rock or if you want to add also value then e.g. #year = 2020
 
]+href="(#[A-Za-z0-9/]*)"[^>]*>[^<]*<\/a>/g, "$1")
            .replace(/ /g, " "); // otherwise .text() below outputs non-breaking space in unicode
        return $("").html(str).text();
    }
    async initEditor() {
        await libraryLoader.requireLibrary(libraryLoader.CKEDITOR);
        this.$widget.show();
        this.$editor.on("click", e => this.handleEditorClick(e));
        this.textEditor = await BalloonEditor.create(this.$editor[0], editorConfig);
        this.textEditor.model.document.on('change:data', () => this.dataChanged());
        // disable spellcheck for attribute editor
        this.textEditor.editing.view.change(writer => writer.setAttribute('spellcheck', 'false', this.textEditor.editing.view.document.getRoot()));
        //await import(/* webpackIgnore: true */'../../libraries/ckeditor/inspector.js');
        //CKEditorInspector.attach(this.textEditor);
    }
    dataChanged() {
        if (this.lastSavedContent === this.textEditor.getData()) {
            this.$saveAttributesButton.fadeOut();
        }
        else {
            this.$saveAttributesButton.fadeIn();
        }
        if (this.$errors.is(":visible")) {
            // using .hide() instead of .slideUp() since this will also hide the error after confirming
            // mention for relation name which suits up. When using.slideUp() error will appear and the slideUp which is weird
            this.$errors.hide();
        }
    }
    async handleEditorClick(e) {
        const pos = this.textEditor.model.document.selection.getFirstPosition();
        if (pos && pos.textNode && pos.textNode.data) {
            const clickIndex = this.getClickIndex(pos);
            let parsedAttrs;
            try {
                parsedAttrs = attributesParser.lexAndParse(this.getPreprocessedData(), true);
            }
            catch (e) {
                // the input is incorrect because user messed up with it and now needs to fix it manually
                return null;
            }
            let matchedAttr = null;
            for (const attr of parsedAttrs) {
                if (clickIndex > attr.startIndex && clickIndex <= attr.endIndex) {
                    matchedAttr = attr;
                    break;
                }
            }
            setTimeout(() => {
                if (matchedAttr) {
                    this.$editor.tooltip('hide');
                    this.attributeDetailWidget.showAttributeDetail({
                        allAttributes: parsedAttrs,
                        attribute: matchedAttr,
                        isOwned: true,
                        x: e.pageX,
                        y: e.pageY
                    });
                }
                else {
                    this.showHelpTooltip();
                }
            }, 100);
        }
        else {
            this.showHelpTooltip();
        }
    }
    showHelpTooltip() {
        this.attributeDetailWidget.hide();
        this.$editor.tooltip({
            trigger: 'focus',
            html: true,
            title: HELP_TEXT,
            placement: 'bottom',
            offset: "0,30"
        });
        this.$editor.tooltip('show');
    }
    getClickIndex(pos) {
        let clickIndex = pos.offset - pos.textNode.startOffset;
        let curNode = pos.textNode;
        while (curNode.previousSibling) {
            curNode = curNode.previousSibling;
            if (curNode.name === 'reference') {
                clickIndex += curNode._attrs.get('notePath').length + 1;
            } else {
                clickIndex += curNode.data.length;
            }
        }
        return clickIndex;
    }
    async loadReferenceLinkTitle(noteId, $el) {
        const note = await treeCache.getNote(noteId, true);
        let title;
        if (!note) {
            title = '[missing]';
        }
        else if (!note.isDeleted) {
            title = note.title;
        }
        else {
            title = note.isErased ? '[erased]' : `${note.title} (deleted)`;
        }
        $el.text(title);
    }
    async refreshWithNote(note) {
        await this.renderOwnedAttributes(note.getOwnedAttributes(), true);
    }
    async renderOwnedAttributes(ownedAttributes, saved) {
        ownedAttributes = ownedAttributes.filter(oa => !oa.isDeleted);
        let htmlAttrs = (await attributeRenderer.renderAttributes(ownedAttributes, true)).html();
        if (htmlAttrs.length > 0) {
            htmlAttrs += " ";
        }
        this.textEditor.setData(htmlAttrs);
        if (saved) {
            this.lastSavedContent = this.textEditor.getData();
            this.$saveAttributesButton.fadeOut(0);
        }
    }
    async focusOnAttributesEvent({tabId}) {
        if (this.tabContext.tabId === tabId) {
            if (this.$editor.is(":visible")) {
                this.$editor.trigger('focus');
                this.textEditor.model.change(writer => { // put focus to the end of the content
                    writer.setSelection(writer.createPositionAt(this.textEditor.model.document.getRoot(), 'end'));
                });
            }
            else {
                this.triggerCommand('focusOnDetail', {tabId: this.tabContext.tabId});
            }
        }
    }
    updateAttributeList(attributes) {
        this.renderOwnedAttributes(attributes, false);
    }
    entitiesReloadedEvent({loadResults}) {
        if (loadResults.getAttributes(this.componentId).find(attr => attr.isAffecting(this.note))) {
            this.refresh();
        }
    }
}