import * as DrawIO from '../services/drawio';
import {MarkdownEditor} from "./index.mjs";
import {EntitySelectorPopup, ImageManager} from "../components";
import {ChangeSpec, SelectionRange, TransactionSpec} from "@codemirror/state";
interface ImageManagerImage {
    id: number;
    name: string;
    thumbs: { display: string; };
    url: string;
}
export class Actions {
    protected readonly editor: MarkdownEditor;
    protected lastContent: { html: string; markdown: string } = {
        html: '',
        markdown: '',
    };
    constructor(editor: MarkdownEditor) {
        this.editor = editor;
    }
    updateAndRender() {
        const content = this.#getText();
        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;
    }
    showImageInsert() {
        const imageManager = window.$components.first('image-manager') as ImageManager;
        imageManager.show((image: ImageManagerImage) => {
            const imageUrl = image.thumbs?.display || image.url;
            const selectedText = this.#getSelectionText();
            const newText = `[](${image.url})`;
            this.#replaceSelection(newText, newText.length);
        }, 'gallery');
    }
    insertImage() {
        const newText = ``;
        this.#replaceSelection(newText, newText.length - 1);
    }
    insertLink() {
        const selectedText = this.#getSelectionText();
        const newText = `[${selectedText}]()`;
        const cursorPosDiff = (selectedText === '') ? -3 : -1;
        this.#replaceSelection(newText, newText.length + cursorPosDiff);
    }
    showImageManager() {
        const selectionRange = this.#getSelectionRange();
        const imageManager = window.$components.first('image-manager') as ImageManager;
        imageManager.show((image: ImageManagerImage) => {
            this.#insertDrawing(image, selectionRange);
        }, 'drawio');
    }
    // Show the popup link selector and insert a link when finished
    showLinkSelector() {
        const selectionRange = this.#getSelectionRange();
        const selector = window.$components.first('entity-selector-popup') as EntitySelectorPopup;
        const selectionText = this.#getSelectionText(selectionRange);
        selector.show(entity => {
            const selectedText = selectionText || entity.name;
            const newText = `[${selectedText}](${entity.link})`;
            this.#replaceSelection(newText, newText.length, selectionRange);
        }, {
            initialValue: selectionText,
            searchEndpoint: '/search/entity-selector',
            entityTypes: 'page,book,chapter,bookshelf',
            entityPermission: 'view',
        });
    }
    // Show draw.io if enabled and handle save.
    startDrawing() {
        const url = this.editor.config.drawioUrl;
        if (!url) return;
        const selectionRange = this.#getSelectionRange();
        DrawIO.show(url, () => Promise.resolve(''), async pngData => {
            const data = {
                image: pngData,
                uploaded_to: Number(this.editor.config.pageId),
            };
            try {
                const resp = await window.$http.post('/images/drawio', data);
                this.#insertDrawing(resp.data as ImageManagerImage, selectionRange);
                DrawIO.close();
            } catch (err) {
                this.handleDrawingUploadError(err);
                throw new Error(`Failed to save image with error: ${err}`);
            }
        });
    }
    #insertDrawing(image: ImageManagerImage, originalSelectionRange: SelectionRange) {
        const newText = `


`, '
');
        } else if (format === '') {
            this.#wrapLine('', '
');
        } else {
            const newFormatIndex = formats.indexOf(format) + 1;
            const newFormat = formats[newFormatIndex];
            const newContent = line.text.replace(matches[0], matches[0].replace(format, newFormat));
            const lineDiff = newContent.length - line.text.length;
            this.#dispatchChange(
                line.from,
                line.to,
                newContent,
                selectionRange.anchor + lineDiff,
                selectionRange.head + lineDiff,
            );
        }
    }
    syncDisplayPosition(event: Event): void {
        // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
        const scrollEl = event.target as HTMLElement;
        const atEnd = Math.abs(scrollEl.scrollHeight - scrollEl.clientHeight - scrollEl.scrollTop) < 1;
        if (atEnd) {
            this.editor.display.scrollToIndex(-1);
            return;
        }
        const blockInfo = this.editor.cm.lineBlockAtHeight(scrollEl.scrollTop);
        const range = this.editor.cm.state.sliceDoc(0, blockInfo.from);
        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.
     */
    async insertTemplate(templateId: string, posX: number, posY: number): Promise {
        const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
        const responseData = (await window.$http.get(`/templates/${templateId}`)).data as {markdown: string, html: string};
        const content = responseData.markdown || responseData.html;
        this.#dispatchChange(cursorPos, cursorPos, content, cursorPos);
    }
    /**
     * Insert multiple images from the clipboard from an event at the provided
     * screen coordinates (Typically form a paste event).
     */
    insertClipboardImages(images: File[], posX: number, posY: number): void {
        const cursorPos = this.editor.cm.posAtCoords({x: posX, y: posY}, false);
        for (const image of images) {
            this.uploadImage(image, cursorPos);
        }
    }
    /**
     * Handle image upload and add image into markdown content
     */
    async uploadImage(file: File, position: number|null = null): Promise {
        if (file === null || file.type.indexOf('image') !== 0) return;
        let ext = 'png';
        if (position === null) {
            position = this.#getSelectionRange().from;
        }
        if (file.name) {
            const fileNameMatches = file.name.match(/\.(.+)$/);
            if (fileNameMatches && 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 placeHolderText = ``;
        this.#dispatchChange(position, position, placeHolderText, position);
        const remoteFilename = `image-${Date.now()}.${ext}`;
        const formData = new FormData();
        formData.append('file', file, remoteFilename);
        formData.append('uploaded_to', this.editor.config.pageId);
        try {
            const image = (await window.$http.post('/images/gallery', formData)).data as ImageManagerImage;
            const newContent = `[](${image.url})`;
            this.#findAndReplaceContent(placeHolderText, newContent);
        } catch (err: any) {
            window.$events.error(err?.data?.message || this.editor.config.text.imageUploadError);
            this.#findAndReplaceContent(placeHolderText, '');
            console.error(err);
        }
    }
    /**
     * Get the current text of the editor instance.
     * @return {string}
     */
    #getText() {
        return this.editor.cm.state.doc.toString();
    }
    /**
     * Set the text of the current editor instance.
     */
    #setText(text: string, selectionRange: SelectionRange|null = null) {
        selectionRange = selectionRange || this.#getSelectionRange();
        const newDoc = this.editor.cm.state.toText(text);
        const newSelectFrom = Math.min(selectionRange.from, newDoc.length);
        const scrollTop = this.editor.cm.scrollDOM.scrollTop;
        this.#dispatchChange(0, this.editor.cm.state.doc.length, text, newSelectFrom);
        this.focus();
        window.requestAnimationFrame(() => {
            this.editor.cm.scrollDOM.scrollTop = scrollTop;
        });
    }
    /**
     * Replace the current selection and focus the editor.
     * Takes an offset for the cursor, after the change, relative to the start of the provided string.
     * Can be provided a selection range to use instead of the current selection range.
     */
    #replaceSelection(newContent: string, cursorOffset: number = 0, selectionRange: SelectionRange|null = null) {
        selectionRange = selectionRange || this.#getSelectionRange();
        const selectFrom = selectionRange.from + cursorOffset;
        this.#dispatchChange(selectionRange.from, selectionRange.to, newContent, selectFrom);
        this.focus();
    }
    /**
     * Get the text content of the main current selection.
     */
    #getSelectionText(selectionRange: SelectionRange|null = null): string {
        selectionRange = selectionRange || this.#getSelectionRange();
        return this.editor.cm.state.sliceDoc(selectionRange.from, selectionRange.to);
    }
    /**
     * Get the range of the current main selection.
     */
    #getSelectionRange(): SelectionRange {
        return this.editor.cm.state.selection.main;
    }
    /**
     * Cleans the given text to work with the editor.
     * Standardises line endings to what's expected.
     */
    #cleanTextForEditor(text: string): string {
        return text.replace(/\r\n|\r/g, '\n');
    }
    /**
     * Find and replace the first occurrence of [search] with [replace]
     */
    #findAndReplaceContent(search: string, replace: string): void {
        const newText = this.#getText().replace(search, replace);
        this.#setText(newText);
    }
    /**
     * Wrap the line in the given start and end contents.
     */
    #wrapLine(start: string, end: string): void {
        const selectionRange = this.#getSelectionRange();
        const line = this.editor.cm.state.doc.lineAt(selectionRange.from);
        const lineContent = line.text;
        let newLineContent;
        let lineOffset = 0;
        if (lineContent.startsWith(start) && lineContent.endsWith(end)) {
            newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
            lineOffset = -(start.length);
        } else {
            newLineContent = `${start}${lineContent}${end}`;
            lineOffset = start.length;
        }
        this.#dispatchChange(line.from, line.to, newLineContent, selectionRange.from + lineOffset);
    }
    /**
     * Dispatch changes to the editor.
     */
    #dispatchChange(from: number, to: number|null = null, text: string|null = null, selectFrom: number|null = null, selectTo: number|null = null): void {
        const change: ChangeSpec = {from};
        if (to) {
            change.to = to;
        }
        if (text) {
            change.insert = text;
        }
        const tr: TransactionSpec = {changes: change};
        if (selectFrom) {
            tr.selection = {anchor: selectFrom};
            if (selectTo) {
                tr.selection.head = selectTo;
            }
        }
        this.editor.cm.dispatch(tr);
    }
    /**
     * Set the current selection range.
     * Optionally will scroll the new range into view.
     * @param {Number} from
     * @param {Number} to
     * @param {Boolean} scrollIntoView
     */
    #setSelection(from: number, to: number, scrollIntoView = false) {
        this.editor.cm.dispatch({
            selection: {anchor: from, head: to},
            scrollIntoView,
        });
    }
}