#include msgbox.jsx
#include comments/api.js

const MszCommentsOptionsLockAction = function(catInfo, reinit) {
    const element = <button class="comments-options-action"/>;

    const setLocked = state => {
        $removeChildren(element);
        if(state) {
            element.appendChild(<i class="fas fa-unlock" />);
            element.appendChild(<span>Unlock</span>);
        } else {
            element.appendChild(<i class="fas fa-lock" />);
            element.appendChild(<span>Lock</span>);
        }
    };

    setLocked(catInfo.locked);

    element.onclick = async () => {
        element.disabled = true;
        try {
            if(!catInfo.locked && !await MszShowConfirmBox(`Are you sure you want to lock comments category ${catInfo.name}?`, 'Locked a comment section'))
                return;

            const result = await MszCommentsApi.updateCategory(catInfo.name, { lock: catInfo.locked ? '0' : '1' });
            if('locked' in result) {
                if(result.locked)
                    catInfo.locked = result.locked;
                else
                    delete catInfo.locked;
            }

            setLocked(catInfo.locked);
            reinit();
        } catch(ex) {
            console.error(ex);
        } finally {
            element.disabled = false;
        }
    };

    return {
        get element() { return element; },
    };
};

const MszCommentsOptionsRetryAction = function(section) {
    const element = <button class="comments-options-action">
        <i class="fas fa-sync-alt" />
        Retry
    </button>;

    element.onclick = async () => {
        element.disabled = true;
        try {
            await section.reload();
        } catch(ex) {
            console.error(ex);
        } finally {
            element.disabled = false;
        }
    };

    return {
        get element() { return element; },
    };
};

const MszCommentsOptions = function() {
    const actions = <div class="comments-options-actions" />;
    const element = <div class="comments-options hidden">
        {actions}
    </div>;

    const hideIfNoChildren = () => {
        element.classList.toggle('hidden', actions.childElementCount < 1);
    };
    hideIfNoChildren();

    return {
        get element() { return element; },

        reset() {
            $removeChildren(actions);
            hideIfNoChildren();
        },

        appendAction(action) {
            actions.appendChild(action.element);
            hideIfNoChildren();
        },
    };
};
