/**
 * Startup file for the MCE visual editor to create the shortcode modal.
 *
 * @module rml_shortcode
 */
import rmlOpts from "rmlopts";
import tinymce from "tinymce";

import { hooks, request } from "./util/index.js";

const TAG = "folder-gallery";

/**
 * This function is fired, when the dialog button "OK" gets pressed.
 *
 * @this tinymce.Editor instance
 */
function submit({ data }) {
    if (!data) {
        return;
    }

    const { fid, link, columns, orderby, size } = data;
    if (fid > -1) {
        let shortcode = `[${TAG} fid="${fid}"`;

        link && link !== "post" && (shortcode += ` link="${link}"`);
        columns && +columns !== 3 && (shortcode += ` columns="${columns}"`);
        if (orderby === true) {
            shortcode += ` orderby="rand"`;
        } else {
            shortcode += ` orderby="rml"`;
        }
        size && size !== "thumbnail" && (shortcode += ` size="${size}"`);

        let sdata = { shortcode };

        /**
         * The shortcode gets generated. You are able to modify the shortcut
         * depending on the modal data.
         *
         * @event module:util/hooks#shortcode/dialog/insert
         * @param {object} shortcodeData
         * @param {object} shortcodeData.shortcode The shortcode which you can modify
         * @param {object} data The data from the dialog
         */
        hooks.call("shortcode/dialog/insert", [sdata, data], this);

        sdata.shortcode += "]";

        this.insertContent(sdata.shortcode);
    }
}

tinymce.PluginManager.add(TAG, function TinyMceRmlShortcode(editor) {
    // Command
    editor.addCommand("folder_gallery_popup", async (ui, v) => {
        // Create tree for listbox
        editor.setProgressState(true);
        const {
            slugs: { names, slugs, types },
        } = await request({
            location: {
                path: "/tree",
            },
        });
        names.shift();
        slugs.shift();
        types.shift();
        const listValues = slugs.map((id, i) => ({
            text: names[i],
            value: id,
            disabled: [1].indexOf(types[i]) > -1,
        }));
        editor.setProgressState(false);

        // Prepare dialog
        const { fid = "", link = "", columns = "3", orderby = "", size = "" } = v || {};
        const columnsValue = [1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => ({ text: `${i}`, value: `${i}` }));
        const { mce } = rmlOpts.others;

        // Show dialog
        let options = {
            title: mce.mceButtonTooltip,
            onsubmit: submit.bind(editor),
            body: [
                {
                    // Add folder select
                    type: "listbox",
                    name: "fid",
                    label: mce.mceBodyGallery,
                    value: fid,
                    values: listValues,
                    tooltip: mce.mceListBoxDirsTooltip,
                },
                {
                    // Add link to select
                    type: "listbox",
                    name: "link",
                    label: mce.mceBodyLinkTo,
                    value: link,
                    values: mce.mceBodyLinkToValues,
                },
                {
                    // Add columns (1-9) to select
                    type: "listbox",
                    name: "columns",
                    label: mce.mceBodyColumns,
                    value: columns,
                    values: columnsValue,
                },
                {
                    // Add random order checkbox
                    type: "checkbox",
                    name: "orderby",
                    label: mce.mceBodyRandomOrder,
                    value: orderby,
                },
                {
                    // Add size to select
                    type: "listbox",
                    name: "size",
                    label: mce.mceBodySize,
                    value: size,
                    values: mce.mceBodySizeValues,
                },
            ],
        };

        /**
         * The shortcode dialog gets opened. You can modify the fields.
         *
         * @event module:util/hooks#shortcode/dialog/open
         * @param {object} options The options
         * @param {object} editor The editor instance
         */
        hooks.call("shortcode/dialog/open", [options, editor]);
        editor.windowManager.open(options);
    });

    // Add tinymce button
    rmlOpts &&
        editor.addButton(TAG, {
            icon: " rmlicon-gallery",
            tooltip: rmlOpts.others.mce.mceButtonTooltip,
            cmd: "folder_gallery_popup",
        });
});
