/** @module others/renderOrderMenu */

import React from "react";

import { Menu, message } from "@devowl-wp/react-folder-tree";

import { applyToAttachmentsBrowser } from "../hooks/sortable.js";
import { IS_DARKMODE, i18n, rmlOpts } from "../util/index.js";

const { Item, SubMenu, Divider } = Menu;

/**
 * An element rendering sortables for the popup menu.
 *
 * @returns React.Element[]
 */
const createSortables = (sortables, select, selectText) =>
    Object.keys(sortables).map((key) => (
        <Item key={key}>
            {sortables[key]} {select === key && <strong>({selectText})</strong>}
        </Item>
    ));

/**
 * Apply an order to a tree node object and afterwards reload the view.
 *
 * @this AppTree
 */
async function applyOrder(selected, key, automatically) {
    if (!rmlOpts.others.isPro && rmlOpts.others.showProHints) {
        this.setState({ showProFeature: "order-content" });
    } else {
        const hide = message.loading(i18n("orderLoadingText", { name: selected.title }));
        const { attachmentsBrowser } = this;
        await selected.applyOrder(key, automatically);

        // Apply props to backbone model
        applyToAttachmentsBrowser(attachmentsBrowser, selected);

        this.handleReload();
        hide();
    }
}

/**
 * When clicking on a menu item in the order menu popup.
 *
 * @this AppTree
 */
async function handleClick({ key, keyPath }) {
    const path = keyPath.reverse();
    const { selected } = this.props.store;
    const _applyOrder = applyOrder.bind(this);
    if (path[0] === "dnd") {
        this.handleOrderClick();
    } else if (path[0] === "applyOnce") {
        // Apply sorting once
        _applyOrder(selected, key);
    } else if (path[0] === "applyAutomatically") {
        _applyOrder(selected, key, true);
    } else if (key === "reset") {
        _applyOrder(selected, "original");
    } else if (key === "resetAutomatically") {
        _applyOrder(selected, "deactivate");
    } else if (key === "applyReindex") {
        _applyOrder(selected, "reindex");
    } else if (key === "applyResetLast") {
        _applyOrder(selected, "last");
    }
}

/**
 * Render the order menu.
 *
 * @type React.Element
 */
export default function () {
    const { store } = this.props;
    const { selected, sortables } = store;
    const isSortable = selected && selected.properties && selected.contentCustomOrder !== 2;

    if (!isSortable) {
        return <Menu style={{ visibility: "hidden" }} />;
    }

    return (
        <Menu onClick={handleClick.bind(this)} theme={IS_DARKMODE ? "dark" : "light"}>
            {!selected.orderAutomatically && <Item key="dnd">{i18n("orderByDnd")}</Item>}
            {selected.contentCustomOrder !== 0 && <Item key="reset">{i18n("resetOrder")}</Item>}
            {!selected.orderAutomatically && (
                <SubMenu key="applyOnce" title={i18n("applyOrderOnce")} disabled={selected.orderAutomatically}>
                    {sortables && createSortables(sortables, selected.lastOrderBy, i18n("last"))}
                </SubMenu>
            )}
            {selected.orderAutomatically && (
                <Item key="resetAutomatically" disabled={selected.contentCustomOrder === 0}>
                    {i18n("deactivateOrderAutomatically")}
                </Item>
            )}
            {
                <SubMenu key="applyAutomatically" title={i18n("applyOrderAutomatically")}>
                    {sortables &&
                        createSortables(sortables, selected.orderAutomatically && selected.lastOrderBy, i18n("latest"))}
                </SubMenu>
            }
            {selected.contentCustomOrder === 1 && <Divider />}
            {selected.contentCustomOrder === 1 && <Item key="applyReindex">{i18n("reindexOrder")}</Item>}
            {selected.contentCustomOrder === 1 && <Item key="applyResetLast">{i18n("resetToLastOrder")}</Item>}
        </Menu>
    );
}
