"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdaptablePopupModuleView = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_redux_1 = require("react-redux");
const DropdownButton_1 = tslib_1.__importDefault(require("../../../../components/DropdownButton"));
const EmptyContent_1 = tslib_1.__importDefault(require("../../../../components/EmptyContent"));
const icons_1 = require("../../../../components/icons");
const AdaptableObjectList_1 = require("../../AdaptableObjectList");
const ButtonNew_1 = require("../../Buttons/ButtonNew");
const PopupPanel_1 = require("./PopupPanel");
const CheckBox_1 = require("../../../../components/CheckBox");
const InternalRedux_1 = require("../../../../Redux/ActionsReducers/InternalRedux");
const SimpleButton_1 = tslib_1.__importDefault(require("../../../../components/SimpleButton"));
const AdaptableContext_1 = require("../../../AdaptableContext");
const react_1 = require("react");
const useRerender_1 = require("../../../../components/utils/useRerender");
const Flex_1 = require("../../../../components/Flex");
const AdaptablePopupModuleView = (props) => {
    /**
     * This triggers a render for each state change.
     * NOT sure this is still needed... It is here for historical reasons.
     */
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const rerender = (0, useRerender_1.useRerender)();
    (0, react_1.useEffect)(() => {
        return adaptable.api.eventApi.on('AdaptableStateChanged', rerender);
    }, [adaptable]);
    const [abObjectType, setAbObjectType] = React.useState(null);
    const moduleInfo = props.module.moduleInfo;
    const items = props.module?.toViewAll();
    const moduleViewProperties = props.module?.getViewProperties?.() ?? {};
    const EditWizard = moduleViewProperties?.getEditWizard?.();
    const [isWizardOpen, setIsWizardOpen] = React.useState(() => {
        return (props.popupParams?.action === 'New' ||
            props.popupParams?.action === 'Edit' ||
            props.popupParams?.action === 'Clone');
    });
    const handleOpenEditPopup = React.useCallback(() => {
        if (EditWizard) {
            setIsWizardOpen(true);
        }
        if (moduleViewProperties.onOpenEditPopup) {
            moduleViewProperties.onOpenEditPopup();
        }
    }, []);
    React.useEffect(() => {
        moduleViewProperties?.onMount?.();
    }, []);
    React.useEffect(() => {
        if (props.popupParams?.action === 'New' ||
            props.popupParams?.action === 'Edit' ||
            props.popupParams?.action === 'Clone') {
            handleOpenEditPopup();
        }
    }, [props.popupParams?.action]);
    const emptyView = moduleViewProperties.emptyView;
    let emptyContent = null;
    if (typeof emptyView === 'function') {
        emptyContent = React.createElement(emptyView, { module: props.module });
    }
    else if (typeof emptyView === 'string') {
        emptyContent = emptyView;
    }
    const toolTipText = moduleViewProperties.newTooltipText ?? `Create ${moduleInfo.FriendlyName}`;
    // Some modules do not have new button
    // e.g. filter
    let newButton = null;
    if (moduleViewProperties?.abObjectTypes?.length) {
        const items = moduleViewProperties?.abObjectTypes.map((abObjectType) => {
            return {
                disabled: abObjectType?.accessLevel === 'ReadOnly',
                onClick: () => {
                    setAbObjectType(abObjectType);
                    handleOpenEditPopup();
                },
                label: abObjectType.label ?? abObjectType.name,
            };
        });
        newButton = (React.createElement(DropdownButton_1.default, { tone: "accent", variant: "raised", columns: ['label'], items: items, tooltip: toolTipText },
            React.createElement(icons_1.Icon, { name: "plus" }),
            " New"));
    }
    else if (!moduleViewProperties.hideNewButton &&
        (EditWizard || moduleViewProperties.onOpenEditPopup)) {
        newButton = (React.createElement(ButtonNew_1.ButtonNew, { onClick: () => handleOpenEditPopup(), tooltip: toolTipText, accessLevel: props.accessLevel }));
    }
    let suspendButton = null;
    const editableObjects = items.filter((item) => !item.abObject.IsReadOnly);
    if (editableObjects.length &&
        moduleViewProperties?.getSuspendAllAction &&
        moduleViewProperties?.getUnSuspendAllAction) {
        const isAtLeastOneAbObjectActive = editableObjects.some((item) => {
            return !item.abObject?.IsSuspended;
        });
        const handleSuspendUnsuspendAll = () => {
            if (isAtLeastOneAbObjectActive) {
                const suspendAllAction = moduleViewProperties.getSuspendAllAction();
                dispatch(suspendAllAction);
            }
            else {
                const unsuspendAllAction = moduleViewProperties.getUnSuspendAllAction();
                dispatch(unsuspendAllAction);
            }
        };
        suspendButton = (React.createElement(SimpleButton_1.default, { className: "twa:mr-2", onMouseDown: () => handleSuspendUnsuspendAll(), tone: isAtLeastOneAbObjectActive ? 'neutral' : 'success', variant: "raised", icon: isAtLeastOneAbObjectActive ? 'pause' : 'resume', accessLevel: props.accessLevel }, isAtLeastOneAbObjectActive ? 'Suspend All' : 'Unsuspend All'));
    }
    const handleWizardClose = () => {
        setAbObjectType(null);
        setIsWizardOpen(false);
        if (['Toolbar', 'ContextMenu', 'ColumnMenu'].includes(props?.popupParams?.source)) {
            props.onClosePopup();
        }
    };
    const adaptableModule = props.api.internalApi
        .getModuleService()
        .getModuleById(props.module.moduleInfo.ModuleName);
    const dispatch = (0, react_redux_1.useDispatch)();
    const showLayoutNonExtendedObjects = (0, react_redux_1.useSelector)((state) => state.Internal.Layout.showLayoutNonExtendedObjects);
    const toggleButtonShowLayoutExtensionObjects = () => {
        if (!adaptableModule?.containsLayoutExtensions()) {
            return;
        }
        if (!props.api.layoutApi.internalApi.hasLayoutSpecificObjects()) {
            return;
        }
        return (React.createElement(Flex_1.Flex, { className: "twa:justify-start" },
            React.createElement(CheckBox_1.CheckBox, { className: "twa:m-0 twa:p-0", checked: showLayoutNonExtendedObjects, onChange: (checked) => dispatch((0, InternalRedux_1.LayoutShowNonExtendedObjects)(checked)) },
                "Show ",
                moduleInfo.FriendlyName,
                "s not available in current Layout")));
    };
    return (React.createElement(PopupPanel_1.PopupPanel, { glyphicon: moduleInfo.Glyph, infoLink: moduleInfo.HelpPage, headerText: moduleInfo.FriendlyName, button: React.createElement(React.Fragment, null,
            suspendButton,
            " ",
            newButton), infoLinkDisabled: !props.api.internalApi.isDocumentationLinksDisplayed() },
        moduleViewProperties.HeaderComponent && React.createElement(moduleViewProperties.HeaderComponent, null),
        toggleButtonShowLayoutExtensionObjects(),
        items?.length ? (React.createElement(AdaptableObjectList_1.AdaptableObjectList, { module: props.module, items: items })) : (React.createElement(EmptyContent_1.default, null, emptyContent ?? `Click 'New' to create a new ${moduleInfo.FriendlyName}`)),
        isWizardOpen && EditWizard && (React.createElement(EditWizard, { abObjectType: abObjectType, moduleInfo: moduleInfo, data: null, popupParams: props.popupParams, configEntities: null, onCloseWizard: handleWizardClose, onFinishWizard: handleWizardClose }))));
};
exports.AdaptablePopupModuleView = AdaptablePopupModuleView;
