
import Ajax from '../ajax.js'
import { es } from './lang/es.js';
import '../../../../../themes/vuexy/js/editorjs/toc.js';
import '../../../../../themes/vuexy/js/editorjs/list.js';
import '../../../../../themes/vuexy/js/editorjs/tune.js';
import '../../../../../themes/vuexy/js/editorjs/table.js';
import '../../../../../themes/vuexy/js/editorjs/columns.js';
import '../../../../../../themes/vuexy/js/editorjs/image.js';
import '../../../../../../themes/vuexy/js/editorjs/alert.js';
import '../../../../../../themes/vuexy/js/editorjs/header.js';
import '../../../../../../themes/vuexy/js/editorjs/drag-drop.js';
import EditorJS from '../../../../../themes/vuexy/js/editorjs.mjs';
import TranslationHelper from '../../common/TranslationHelper.js';
import { alertConfirmAction, alertError, alertSuccess, alertWarning } from '../alerts/sweetAlert.js';

import WikiSectionForm from '../forms/WikiSectionForm.js'



class WikiEditor extends TranslationHelper {
    constructor() {
        super();
        this.sectionId = $("#wiki-section-id").val();

        this.wikiFormSection = new WikiSectionForm()
        this.wikiFormSection.setId(this.sectionId)
    }
    async initEditor() {
        this.wikiFormSection.init()
        const editorJSConfig = {
            tools: {
                image: {
                    class: ImageTool,
                    config: {
                        features: {
                            border: true,
                            caption: 'optional',
                            stretch: false
                        },
                        endpoints: {
                            byFile: `/wiki/file/upload/${this.sectionId}`, // Your backend file uploader endpoint
                            byUrl: 'fetchUrl', // Your endpoint that provides uploading by Url
                        }
                    }
                },
            }
        };
        await this.get_translations("Wiki")
        this.editor = new EditorJS({
            holder: 'editorjs',
            i18n: this.locale == "es" ? es : null,
            autofocus: true,
            readOnly: true,
            tunes: {
                alignment: {
                    class: AlignmentBlockTune,
                },
            },
            tools: {

                twoColumns: {
                    class: EditorJSLayout.LayoutBlockTool,
                    shortcut: "CMD+2",
                    toolbox: {
                        icon: `
                            <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="24"
                            height="24"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            >
                            <path d="M3 3m0 1a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v16a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1zm9 -1v18" />
                            </svg>
                        `,
                        title: "2 Columns",
                    },
                    config: {
                        EditorJS,
                        editorJSConfig,
                        enableLayoutEditing: true,
                        enableLayoutSaving: true,
                        initialData: {
                            itemContent: {
                                1: {
                                    blocks: [],
                                },
                                2: {
                                    blocks: [],
                                },
                            },
                            layout: {
                                type: "div",
                                id: "",
                                className: "col-md-12 layout-block",
                                style: "display: flex; justify-content: space-around; padding: 16px;width:100%;",
                                children: [
                                    {
                                        type: "item",
                                        id: "",
                                        style: "display: inline-block; ",
                                        className: "col-md-6 layout-block",
                                        itemContentId: "1",
                                    },
                                    {
                                        type: "item",
                                        id: "",
                                        className: "col-md-6 layout-block",
                                        style: "display: inline-block; ",
                                        itemContentId: "2",
                                    },
                                ],
                            },
                        },
                    }
                },
                toc: TOC,
                header: {
                    class: Header,
                    tunes: ['alignment'],
                    config: {
                        placeholder: "",
                        levels: [1, 2, 3, 4],
                        defaultLevel: 1
                    },
                },
                nestedchecklist: {
                    class: editorjsNestedChecklist,
                    config: {
                        maxLevel: 1,
                    }
                },
                alert: {
                    class: Alert,
                    inlineToolbar: true,
                    tunes: ['alignment'],
                    config: {
                        alertTypes: ['primary', 'secondary', 'info', 'success', 'warning', 'danger', 'light', 'dark'],
                        defaultType: 'primary',
                        messagePlaceholder: 'Introduzca texto',
                    },
                },
                image: {
                    class: ImageTool,
                    config: {
                        features: {
                            border: true,
                            caption: 'optional',
                            stretch: false
                        },
                        endpoints: {
                            byFile: `/wiki/file/upload/${this.sectionId}`, // Your backend file uploader endpoint
                            byUrl: 'fetchUrl', // Your endpoint that provides uploading by Url
                        }
                    }
                },
                table: {
                    class: Table,
                    tunes: ['alignment'],
                    inlineToolbar: true,
                    config: {
                        rows: 2,
                        cols: 3,
                        maxRows: 5,
                        maxCols: 5,
                    },
                },
                alignment: {
                    class: AlignmentBlockTune,
                    config: {
                        default: "left",
                        blocks: {
                            header: 'left',
                            list: 'left'
                        }
                    }
                },


            },
        })
    }
    async initViewOnly() {
        try {
            await this.initEditor()
            await this.editor.isReady;
            this.handleGetDataPublished();
        } catch (reason) {
            console.log(`Editor.js initialization failed because of ${reason}`)
        }
    }
    async init() {
        try {
            await this.initEditor()
            $('#release-editor').attr('disabled', 'disabled')
            $('#save-editor').attr('disabled', 'disabled')
            await this.editor.isReady;
            new DragDrop(this.editor);
            /** Do anything you need after editor initialization */
            $('#save-editor').on('click', () => {
                this.editor.save().then(outputData => {
                    alertConfirmAction(this.get_lang('save_content')).then(result => {
                        if (result.isConfirmed) {
                            this.handleSaveContent(outputData)
                        }
                    });
                })

            })
            $('#release-editor').on('click', () => {

                this.editor.save().then(outputData => {
                    alertConfirmAction(this.get_lang('release_content')).then(result => {
                        if (result.isConfirmed) {
                            this.handlePublishContent(outputData)
                        }
                        console.log(result)
                    });
                }).catch((error) => {
                    alertError(this.get_lang('need_editor_to_save')).fire()
                })

            })

            $('#preview-editor').on('click', () => {
                this.editor.readOnly.toggle()
                $('#edit-editor').removeClass('d-none')
                $('#preview-editor').addClass('d-none')
                $('#release-editor').attr('disabled', 'disabled')
                $('#save-editor').attr('disabled', 'disabled')
            })
            $('#edit-editor').on('click', () => {
                this.editor.readOnly.toggle()
                $('#edit-editor').addClass('d-none')
                $('#preview-editor').removeClass('d-none')

                $('#release-editor').attr('disabled', null)
                $('#save-editor').attr('disabled', null)
            })
            this.handleGetData();
        } catch (reason) {
            console.log(`Editor.js initialization failed because of ${reason}`)
        }
    }

    handleGetData() {
        const ajax = new Ajax(`/wiki/section/${this.sectionId}`,
            null,
            null,
            this.handleGetDataSuccess.bind(this),
            this.handleGetDataError.bind(this))
        ajax.get()
    }
    handleGetDataSuccess(response) {
        if (response.data.contents?.editor_data) {
            alertSuccess(response.message).fire()
            this.renderContent(response.data.contents.editor_data)
        } else {
            alertWarning('No hay contenido').fire()

        }
    }
    handleGetDataError(error) {
        console.log(error)
    }
    handleGetDataPublished() {
        const ajax = new Ajax(`/wiki/section/${this.sectionId}`,
            null,
            null,
            this.handleGetDataPublishedSuccess.bind(this),
            this.handleGetDataPublishedError.bind(this))
        ajax.get()
    }
    handleGetDataPublishedSuccess(response) {
        if (response.data.contents?.published_data) {
            alertSuccess(response.message).fire()
            this.renderContent(response.data.contents.published_data)
        } else {
            alertWarning(this.get_lang('no_content')).fire()
        }
    }
    handleGetDataPublishedError(error) {
        alertError(error.error).fire()

    }
    renderContent(content) {
        try {
            let parsedContent = JSON.parse(content)
            this.editor.render(parsedContent)
            this.centerImages()
        } catch (error) {
            console.log(error)
        }
    }
    handleSaveContent(data) {

        const ajax = new Ajax(`/wiki/save/${this.sectionId}`,
            data,
            null,
            this.handleSaveContentSuccess.bind(this),
            this.handleSaveContentError.bind(this))
        ajax.post()
    }
    handleSaveContentSuccess(response) {
        this.handleGetData()
    }
    handleSaveContentError(response) { }
    handlePublishContent(data) {
        const ajax = new Ajax(`/wiki/publish/${this.sectionId}`,
            data,
            null,
            this.handleSaveContentSuccess.bind(this),
            this.handleSaveContentError.bind(this))
        ajax.post()
    }
    handleSaveContentSuccess(response) {
        this.handleGetData()
    }
    handleSaveContentError(response) { }
    centerImages() {
        setInterval(() => {

            $(".image-tool img").css('margin', '0 auto')
            $(".image-tool__caption").css('margin', '0 auto').css('border', 'none').css('text-align', 'center').css('box-shadow', 'none')

        }, 500)
    }

}
export default WikiEditor