"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Item
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Toolbar = void 0;
const React = require("react");
const core_bentley_1 = require("@itwin/core-bentley");
const core_react_1 = require("@itwin/core-react");
const appui_layout_react_1 = require("@itwin/appui-layout-react");
const ActionButtonItemDef_1 = require("../shared/ActionButtonItemDef");
const CustomItemDef_1 = require("../shared/CustomItemDef");
const SyncUiEventDispatcher_1 = require("../syncui/SyncUiEventDispatcher");
const UiFramework_1 = require("../UiFramework");
const GroupItem_1 = require("./GroupItem");
/** Toolbar React component.
 * @internal
 */
class Toolbar extends React.Component {
    constructor(props) {
        super(props);
        this._dimension = 0;
        this._minToolbarSize = (ActionButtonItemDef_1.ActionButtonItemDef.defaultButtonSize + 2);
        this._isMounted = false;
        this._handleSyncUiEvent = (args) => {
            if (this._processSyncUiEvent(this.props.items, args)) {
                setTimeout(() => {
                    // if sync event changed number of displayable buttons layout the toolbar and re-render
                    const items = this.generateToolbarItems(this.props.items, new core_react_1.Size(this.state.width, this.state.height));
                    if (this._isMounted)
                        this.setState({ items });
                });
            }
        };
        // istanbul ignore next - currently unable to replicate resizing in unit test
        this._onResize = (width, height) => {
            width = width !== null && width !== void 0 ? width : this._minToolbarSize;
            height = height !== null && height !== void 0 ? height : this._minToolbarSize;
            // do allow toolbar to go to a size that doesn't show at least one button;
            if (width < this._minToolbarSize)
                width = this._minToolbarSize;
            if (height < this._minToolbarSize)
                height = this._minToolbarSize;
            if (this.state.width !== width || this.state.height !== height) {
                const items = this.generateToolbarItems(this.props.items, new core_react_1.Size(width, height));
                if (this._isMounted)
                    this.setState({ width, height, items });
            }
        };
        const itemList = this.props.items;
        // Filter on GroupItemDef
        itemList.forEach((item) => {
            if (item instanceof GroupItem_1.GroupItemDef) {
                // istanbul ignore else
                if (!item.directionExplicit && this.props.expandsTo !== undefined) // eslint-disable-line deprecation/deprecation
                    item.direction = this.props.expandsTo; // eslint-disable-line deprecation/deprecation
            }
        });
        // pick a reasonable initial size, when zone layout occurs a resize event will trigger to adjust this size.
        let width = (ActionButtonItemDef_1.ActionButtonItemDef.defaultButtonSize + 2) * 3;
        let height = width;
        // istanbul ignore next
        if (props.initialSize) {
            width = props.initialSize.width;
            height = props.initialSize.height;
        }
        const items = this.generateToolbarItems(this.props.items, new core_react_1.Size(width, height));
        // let's set the default size big enough to hold a single button.
        this.state = {
            width,
            height,
            items,
        };
    }
    get _toolbarId() {
        return this.props.toolbarId ? this.props.toolbarId : "unknown";
    }
    componentDidMount() {
        this._isMounted = true;
        SyncUiEventDispatcher_1.SyncUiEventDispatcher.onSyncUiEvent.addListener(this._handleSyncUiEvent);
    }
    componentWillUnmount() {
        this._isMounted = false;
        SyncUiEventDispatcher_1.SyncUiEventDispatcher.onSyncUiEvent.removeListener(this._handleSyncUiEvent);
    }
    componentDidUpdate(prevProps, _prevState) {
        if (this.props.items !== prevProps.items) {
            // if sync event changed number of displayable buttons layout the toolbar and re-render
            const items = this.generateToolbarItems(this.props.items, new core_react_1.Size(this.state.width, this.state.height));
            this.setState({ items });
        }
    }
    setCurrentStateValues(item) {
        // if a stateFunc is specified call it to get current state values
        // istanbul ignore else
        if (item.stateFunc) { // eslint-disable-line deprecation/deprecation
            const itemState = item.stateFunc({
                isVisible: item.isVisible, isEnabled: item.isEnabled, isPressed: item.isPressed, isActive: item.isActive, // eslint-disable-line deprecation/deprecation
            });
            item.isVisible = !!itemState.isVisible; // eslint-disable-line deprecation/deprecation
            item.isEnabled = !!itemState.isEnabled; // eslint-disable-line deprecation/deprecation
            item.isPressed = !!itemState.isPressed;
            item.isActive = !!itemState.isActive;
            return true;
        }
        // istanbul ignore next
        return false;
    }
    _processSyncUiEvent(itemList, args) {
        // istanbul ignore next
        if (!itemList || 0 === itemList.length)
            return false;
        let returnValue = false;
        // Review all the itemDefs to see if any are monitoring sync events in UiSyncEventArgs
        for (const item of itemList) {
            if (item.stateFunc && item.stateSyncIds && item.stateSyncIds.length > 0 && // eslint-disable-line deprecation/deprecation
                item.stateSyncIds.some((value) => args.eventIds.has(value.toLowerCase()))) { // eslint-disable-line deprecation/deprecation
                if (item instanceof GroupItem_1.GroupItemDef) {
                    this.setCurrentStateValues(item);
                    this._processSyncUiEvent(item.items, args);
                }
                else {
                    this.setCurrentStateValues(item);
                }
                returnValue = true;
            }
            else {
                // istanbul ignore next
                if (item instanceof GroupItem_1.GroupItemDef) {
                    if (this._processSyncUiEvent(item.items, args))
                        returnValue = true;
                }
            }
        }
        return returnValue;
    }
    layoutToolbarItems(itemList) {
        // istanbul ignore next -
        if (0 === itemList.length)
            return [];
        core_bentley_1.Logger.logInfo(UiFramework_1.UiFramework.loggerCategory(this), `Available space for toolbar [${this._toolbarId}] = ${this._dimension}`);
        const actionItems = new Array();
        let itemDimensions = 0;
        // Filter on ActionButtonItemDef
        itemList.forEach((item) => {
            // istanbul ignore else
            if (item.isVisible) { // eslint-disable-line deprecation/deprecation
                // istanbul ignore else
                if (item instanceof ActionButtonItemDef_1.ActionButtonItemDef) {
                    actionItems.push(item);
                }
            }
        });
        // Populate the overflow button
        let overflowItemDef;
        if (actionItems.length > 1) {
            // Get the item dimensions
            actionItems.forEach((item) => {
                const itemSize = item.getDimension(this.props.orientation) + 1;
                itemDimensions += itemSize;
                core_bentley_1.Logger.logTrace(UiFramework_1.UiFramework.loggerCategory(this), `  Item [${item.id ? item.id : /* istanbul ignore next */ item.label}] has a size of ${itemSize} cumulative size=${itemDimensions}.`);
            });
            core_bentley_1.Logger.logInfo(UiFramework_1.UiFramework.loggerCategory(this), `  Needed toolbar size [${this._toolbarId}] = ${itemDimensions}`);
            // istanbul ignore next - currently unable to set size in unit test
            const padding = 2; // used just to insure button will fall inside tool box
            if (itemDimensions > (this._dimension - padding)) {
                const overflowItems = [];
                const lastItemIndex = actionItems.length - 1;
                let singleItemSize = 0;
                for (let index = lastItemIndex; index >= 0; index--) {
                    // istanbul ignore next
                    if (actionItems[index] instanceof CustomItemDef_1.CustomItemDef)
                        continue;
                    if (0 === singleItemSize)
                        singleItemSize = actionItems[index].getDimension(this.props.orientation);
                    const deletedItems = actionItems.splice(index, 1);
                    // istanbul ignore else
                    if (deletedItems.length === 1) {
                        const item = deletedItems[0];
                        overflowItems.unshift(item);
                        core_bentley_1.Logger.logTrace(UiFramework_1.UiFramework.loggerCategory(this), `  * Item [${item.id ? item.id : /* istanbul ignore next */ item.label}] put into overflow items.`);
                        let currentWidth = 0;
                        actionItems.forEach((itemDef) => currentWidth += (itemDef.getDimension(this.props.orientation) + 1));
                        itemDimensions = (currentWidth + singleItemSize);
                        if (itemDimensions < (this._dimension - padding))
                            break;
                    }
                }
                overflowItemDef = new GroupItem_1.GroupItemDef({
                    groupId: `overflow-group-${itemDimensions}-${actionItems.length}-${overflowItems.length}`,
                    labelKey: "UiFramework:general.overflow",
                    items: overflowItems,
                    direction: this.props.expandsTo,
                });
                overflowItemDef.overflow = true;
            }
        }
        // Populate the toolbar items
        const toolbarItems = actionItems.map((item, index) => {
            return item.toolbarReactNode(index);
        });
        // istanbul ignore next - currently unsure how to trigger sizing/resizing so overflow is never populated
        if (overflowItemDef)
            toolbarItems.push(overflowItemDef.toolbarReactNode()); // eslint-disable-line deprecation/deprecation
        return toolbarItems;
    }
    generateToolbarItems(itemList, size) {
        this._dimension = (this.props.orientation === core_react_1.Orientation.Horizontal ? size.width : size.height);
        // istanbul ignore next - since sizing is not working in unit test size and dimension always set to default of 42
        if (this._dimension < this._minToolbarSize)
            this._dimension = this._minToolbarSize;
        return this.layoutToolbarItems(itemList);
    }
    hasVisibleItems(items) {
        for (const item of items) {
            // istanbul ignore else
            if (item && item.isVisible) // eslint-disable-line deprecation/deprecation
                return true;
        }
        // istanbul ignore next
        return false;
    }
    render() {
        // istanbul ignore next
        if (0 === this.props.items.length || !this.hasVisibleItems(this.props.items)) {
            core_bentley_1.Logger.logTrace(UiFramework_1.UiFramework.loggerCategory(this), `--->  nothing to render for ${this._toolbarId} `);
            return null;
        }
        core_bentley_1.Logger.logTrace(UiFramework_1.UiFramework.loggerCategory(this), `---> render ${this._toolbarId} `);
        return (React.createElement(core_react_1.ResizableContainerObserver, { onResize: this._onResize },
            React.createElement(appui_layout_react_1.Toolbar // eslint-disable-line deprecation/deprecation
            , { style: this.props.style, className: this.props.className, expandsTo: this.props.expandsTo, panelAlignment: this.props.panelAlignment, items: React.createElement(React.Fragment, null, this.state.items) })));
    }
}
exports.Toolbar = Toolbar;
//# sourceMappingURL=Toolbar.js.map