import {Jodit, IJoditEditorProps} from "jodit-react"
import Router from "@/routing/router";
import {PARAGRAPH} from "jodit/esm/core/constants";

export class Configuration {
    public static CONTENT_EDITABLE_DATA_ATTRIBUBTE = 'data-content-editable';
    private form: HTMLFormElement | null = null;

    constructor(
        private jodit: Jodit,
    ) {
        this.form = this.jodit.editor.closest("form");
    }

    private addContentEditable(): void {
        const editableElements = this.jodit.editor.querySelectorAll(`[${Configuration.CONTENT_EDITABLE_DATA_ATTRIBUBTE}]`);
        editableElements.forEach(element => {
            element.setAttribute('contenteditable', 'true');
        });
    }

    private removeContentEditable(): void {
        const editableElements = this.jodit.editor.querySelectorAll(`[${Configuration.CONTENT_EDITABLE_DATA_ATTRIBUBTE}]`);
        editableElements.forEach(element => {
            element.removeAttribute('contenteditable');
        });
    }

    /**
     * Zatím vypnuto!
     */
    private backspaceHandler(event: any): void {
        const selection = this.jodit.selection;
        const editedNode = selection.current();
        if (!editedNode) {
            return;
        }

        const editedElement = editedNode instanceof Element ? editedNode : editedNode.parentElement;
        if (!editedElement) {
            return; // Pokud se nenajde element, tak nemá smysl pokračovat
        }

        const editableElement = editedElement.closest(`[${Configuration.CONTENT_EDITABLE_DATA_ATTRIBUBTE}]`);
        if (!editableElement) {
            return; // Pokud žádný parent není editable, tak nás událost nezajimá
        }

        // Najde všechny děti aktuálního `contenteditable` elementu
        const children = Array.from(editableElement.childNodes)
            .filter(node => node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE);
        // Pokud je prázdný nebo obsahuje jen jeden prvek, zabrání odstranění
        if (children.length > 1 || (children[0] && children[0]?.textContent?.trim() !== '')) {
            return;
        }

        event.preventDefault(); // Pokud je 0 potomků, tak zabráníme mazání
        if (editedElement instanceof HTMLBRElement) {
            return;
        }
        if (children.length !== 0) {
            return;
        }

        // Element tvoříme ať už byl jeden potomek a došlo ke smazání, nebo žádný potomek a mazání nebylo umožněno. vždy tam chceme odstavec
        const paragraph = document.createElement('p');
        paragraph.innerHTML = '<br>';
        editedElement.appendChild(paragraph);

        // Nastaví kurzor do nového odstavce
        selection.setCursorIn(paragraph, true);
    }

    public static getConfiguration(): IJoditEditorProps["config"] {
        return {
            readonly: false,
            tabIndex: 1,
            iframe: false,
            language: 'cs_cz',
            uploader: {
                url: Router.generate("ApiV1FileManager", {"action": "fileUpload"}),
                // @ts-ignore
                baseURL: "data/storage/",
                insertImageAsBase64URI: false,
                imagesExtensions: ['jpg', 'jpeg', 'png', 'gif'],
            },
            filebrowser: {
                fullsize: true,
                preview: true,
                contextMenu: true,
                editImage: true,
                createNewFolder: true,
                deleteFolder: true,
                renameFolder: true,
                moveFolder: true,
                moveFile: true,
                showFoldersPanel: true,
                showFileName: true,
                showFileSize: true,
                showFileChangeTime: true,
                // @ts-ignore
                shadowRoot: true,
                ajax: {
                    url: Router.generate("ApiV1FileManager"),  // URL pro procházení a správu souborů
                },
                saveStateInStorage: {
                    storeLastOpenedFolder: false,
                    storeView: true,
                    storeSortBy: true,
                },
            },
            draggableTags: ['img', 'iframe', 'jodit', 'jodit-media'],
            enter: PARAGRAPH,
        };
    }

    public execute() {
        this.jodit.events.on('afterInit', () => this.addContentEditable());
        // this.jodit.events.on('keydown', (event) => {
        //     if (event.key === 'Backspace') {
        //         this.backspaceHandler(event);
        //     }
        // });

        this.form?.addEventListener("submit", () => this.removeContentEditable());
    }
}