import DrawIO from "../services/drawio";
export class Actions {
    /**
     * @param {MarkdownEditor} editor
     */
    constructor(editor) {
        this.editor = editor;
        this.lastContent = {
            html: '',
            markdown: '',
        };
    }
    updateAndRender() {
        const content = this.editor.cm.getValue();
        this.editor.config.inputEl.value = content;
        const html = this.editor.markdown.render(content);
        window.$events.emit('editor-html-change', '');
        window.$events.emit('editor-markdown-change', '');
        this.lastContent.html = html;
        this.lastContent.markdown = content;
        this.editor.display.patchWithHtml(html);
    }
    getContent() {
        return this.lastContent;
    }
    insertImage() {
        const cursorPos = this.editor.cm.getCursor('from');
        /** @type {ImageManager} **/
        const imageManager = window.$components.first('image-manager');
        imageManager.show(image => {
            const imageUrl = image.thumbs.display || image.url;
            let selectedText = this.editor.cm.getSelection();
            let newText = "[](" + image.url + ")";
            this.editor.cm.focus();
            this.editor.cm.replaceSelection(newText);
            this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
        }, 'gallery');
    }
    insertLink() {
        const cursorPos = this.editor.cm.getCursor('from');
        const selectedText = this.editor.cm.getSelection() || '';
        const newText = `[${selectedText}]()`;
        this.editor.cm.focus();
        this.editor.cm.replaceSelection(newText);
        const cursorPosDiff = (selectedText === '') ? -3 : -1;
        this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
    }
    showImageManager() {
        const cursorPos = this.editor.cm.getCursor('from');
        /** @type {ImageManager} **/
        const imageManager = window.$components.first('image-manager');
        imageManager.show(image => {
            this.insertDrawing(image, cursorPos);
        }, 'drawio');
    }
    // Show the popup link selector and insert a link when finished
    showLinkSelector() {
        const cursorPos = this.editor.cm.getCursor('from');
        /** @type {EntitySelectorPopup} **/
        const selector = window.$components.first('entity-selector-popup');
        selector.show(entity => {
            let selectedText = this.editor.cm.getSelection() || entity.name;
            let newText = `[${selectedText}](${entity.link})`;
            this.editor.cm.focus();
            this.editor.cm.replaceSelection(newText);
            this.editor.cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
        });
    }
    // Show draw.io if enabled and handle save.
    startDrawing() {
        const url = this.editor.config.drawioUrl;
        if (!url) return;
        const cursorPos = this.editor.cm.getCursor('from');
        DrawIO.show(url,() => {
            return Promise.resolve('');
        }, (pngData) => {
            const data = {
                image: pngData,
                uploaded_to: Number(this.editor.config.pageId),
            };
            window.$http.post("/images/drawio", data).then(resp => {
                this.insertDrawing(resp.data, cursorPos);
                DrawIO.close();
            }).catch(err => {
                this.handleDrawingUploadError(err);
            });
        });
    }
    insertDrawing(image, originalCursor) {
        const newText = `


`, '
');
        } else if (format === '') {
            this.wrapLine('', '
');
        } else {
            const newFormatIndex = formats.indexOf(format) + 1;
            const newFormat = formats[newFormatIndex];
            const newContent = lineContent.replace(matches[0], matches[0].replace(format, newFormat));
            this.editor.cm.replaceRange(newContent, contentRange.anchor, contentRange.head);
            const chDiff = newContent.length - lineContent.length;
            selectionRange.anchor.ch += chDiff;
            if (selectionRange.anchor !== selectionRange.head) {
                selectionRange.head.ch += chDiff;
            }
            this.editor.cm.setSelection(selectionRange.anchor, selectionRange.head);
        }
    }
    /**
     * Handle image upload and add image into markdown content
     * @param {File} file
     */
    uploadImage(file) {
        if (file === null || file.type.indexOf('image') !== 0) return;
        let ext = 'png';
        if (file.name) {
            let fileNameMatches = file.name.match(/\.(.+)$/);
            if (fileNameMatches.length > 1) ext = fileNameMatches[1];
        }
        // Insert image into markdown
        const id = "image-" + Math.random().toString(16).slice(2);
        const placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
        const selectedText = this.editor.cm.getSelection();
        const placeHolderText = ``;
        const cursor = this.editor.cm.getCursor();
        this.editor.cm.replaceSelection(placeHolderText);
        this.editor.cm.setCursor({line: cursor.line, ch: cursor.ch + selectedText.length + 3});
        const remoteFilename = "image-" + Date.now() + "." + ext;
        const formData = new FormData();
        formData.append('file', file, remoteFilename);
        formData.append('uploaded_to', this.editor.config.pageId);
        window.$http.post('/images/gallery', formData).then(resp => {
            const newContent = `[](${resp.data.url})`;
            this.findAndReplaceContent(placeHolderText, newContent);
        }).catch(err => {
            window.$events.emit('error', this.editor.config.text.imageUploadError);
            this.findAndReplaceContent(placeHolderText, selectedText);
            console.log(err);
        });
    }
    syncDisplayPosition() {
        // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
        const scroll = this.editor.cm.getScrollInfo();
        const atEnd = scroll.top + scroll.clientHeight === scroll.height;
        if (atEnd) {
            this.editor.display.scrollToIndex(-1);
            return;
        }
        const lineNum = this.editor.cm.lineAtHeight(scroll.top, 'local');
        const range = this.editor.cm.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
        const parser = new DOMParser();
        const doc = parser.parseFromString(this.editor.markdown.render(range), 'text/html');
        const totalLines = doc.documentElement.querySelectorAll('body > *');
        this.editor.display.scrollToIndex(totalLines.length);
    }
    /**
     * Fetch and insert the template of the given ID.
     * The page-relative position provided can be used to determine insert location if possible.
     * @param {String} templateId
     * @param {Number} posX
     * @param {Number} posY
     */
    insertTemplate(templateId, posX, posY) {
        const cursorPos = this.editor.cm.coordsChar({left: posX, top: posY});
        this.editor.cm.setCursor(cursorPos);
        window.$http.get(`/templates/${templateId}`).then(resp => {
            const content = resp.data.markdown || resp.data.html;
            this.editor.cm.replaceSelection(content);
        });
    }
    /**
     * Insert multiple images from the clipboard.
     * @param {File[]} images
     */
    insertClipboardImages(images) {
        const cursorPos = this.editor.cm.coordsChar({left: event.pageX, top: event.pageY});
        this.editor.cm.setCursor(cursorPos);
        for (const image of images) {
            this.uploadImage(image);
        }
    }
}