/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Picker
 */
import "./ListPicker.scss";
import classnames from "classnames";
import * as React from "react";
import { PopupItem } from "@itwin/components-react";
import { Icon, SearchBox, withOnOutsideClick } from "@itwin/core-react";
import { containHorizontally, ExpandableItem, Group, GroupColumn, Item, Panel, withContainIn } from "@itwin/appui-layout-react";
import { FrameworkVersionSwitch } from "../hooks/useFrameworkVersion";
import { ToolbarDragInteractionContext } from "../toolbar/DragInteraction";
import { UiFramework } from "../UiFramework";
import { InternalFrontstageManager } from "../frontstage/InternalFrontstageManager";
// eslint-disable-next-line @typescript-eslint/naming-convention, deprecation/deprecation
const ContainedGroup = withOnOutsideClick(withContainIn(Group), undefined, false);
/** Enum for the list picker item type
 * @beta
 */
export var ListItemType;
(function (ListItemType) {
    ListItemType[ListItemType["Item"] = 0] = "Item";
    ListItemType[ListItemType["Separator"] = 1] = "Separator";
    ListItemType[ListItemType["Container"] = 2] = "Container";
})(ListItemType || (ListItemType = {}));
let lastOpenedPicker; // eslint-disable-line deprecation/deprecation
/** List Picker Item React component
 * @beta
 */
export class ListPickerItem extends React.PureComponent {
    /** Renders ListPickerItem */
    render() {
        const itemClassName = classnames("ListPicker-item", this.props.isActive && "is-active", this.props.isFocused && "is-focused", this.props.className);
        // TODO - if cut off, show a title
        const title = (this.props.label && this.props.label.length > 25) ? this.props.label : undefined;
        return (
        // eslint-disable-next-line jsx-a11y/click-events-have-key-events
        React.createElement("div", { className: itemClassName, onClick: this.props.onClick, role: "button", tabIndex: -1 },
            React.createElement("div", { className: "label", title: title }, this.props.label)));
    }
}
/** Expandable Section React component used by [[ListPickerBase]]
 * @beta
 */
export class ExpandableSection extends React.PureComponent {
    /** Creates an ExpandableSection */
    constructor(props) {
        super(props);
        this._onClick = () => {
            this.setState((prevState) => ({ expanded: !prevState.expanded }));
        };
        this.state = { expanded: !!this.props.expanded };
    }
    /** Renders ExpandableSection */
    render() {
        const className = classnames("nz-toolbar-item-expandable-group-group", this.props.className);
        const icon = this.state.expanded ? React.createElement("i", { className: "icon icon-chevron-down" }) : React.createElement("i", { className: "icon icon-chevron-right" });
        return (React.createElement(Panel, { className: className, style: this.props.style, key: this.props.title },
            " ",
            React.createElement("div", { onClick: this._onClick, className: this.state.expanded ? "ListPickerInnerContainer-header-expanded" : "ListPickerInnerContainer-header", role: "button", tabIndex: -1, "aria-expanded": this.state.expanded },
                React.createElement("div", { className: "ListPickerInnerContainer-header-content" },
                    React.createElement("div", { className: "ListPickerInnerContainer-expander" }, icon),
                    React.createElement("div", { className: "ListPickerInnerContainer-title" }, this.props.title))),
            this.state.expanded ?
                React.createElement(GroupColumn, null,
                    " ",
                    this.props.children) : React.createElement("div", null)));
    }
}
/** @beta */
export function getListPanel(props) {
    const expandSingleSection = () => {
        const populatedContainers = props.items.filter((item) => {
            return (item.type === ListItemType.Container && item.children.length !== 0);
        });
        return populatedContainers.length === 1;
    };
    const listItemToElement = (item, itemIndex) => {
        switch (item.type) {
            case ListItemType.Item:
                return (React.createElement(ListPickerItem, { ...props, key: itemIndex.toString(), label: item.name, isActive: item.enabled, onClick: 
                    // istanbul ignore next
                    () => { props.setEnabled(item, !item.enabled); } }));
            case ListItemType.Separator:
                return (React.createElement("div", { key: itemIndex.toString(), className: "ListPicker-separator" }));
            case ListItemType.Container:
                if (item.children.length !== 0) {
                    return (React.createElement(ExpandableSection, { key: itemIndex.toString(), title: item.name, className: "ListPickerInnerContainer", expanded: expandSingleSection() },
                        React.createElement(GroupColumn, null,
                            " ",
                            item.children.map(listItemToElement))));
                }
                else {
                    return (React.createElement("div", { key: itemIndex.toString() }));
                }
            // istanbul ignore next
            default:
                return (React.createElement("div", { key: itemIndex.toString() }));
        }
    };
    return (React.createElement(ContainedGroup, { className: "ListPickerContainer", columns: React.createElement(GroupColumn, { className: "ListPicker-column" },
            " ",
            props.items.map(listItemToElement)), containFn: containHorizontally, title: props.title, header: props.searchBox && props.onSearchValueChange &&
            React.createElement(SearchBox, { className: "ListPickerSearchBox", onValueChanged: props.onSearchValueChange }) }));
}
/**
 * List picker base class.
 * Used to provide an expandable list of items to enable/disable items.
 * @deprecated in 3.5. Used in UI1.0 only.
 * @beta
 */
export class ListPickerBase extends React.PureComponent {
    /** Creates a ListPickerBase */
    constructor(props) {
        super(props);
        this._isMounted = false;
        this._closeOnPanelOpened = true;
        this._ref = React.createRef();
        /** Minimizes the expandable component. */
        this.minimize = () => {
            // istanbul ignore else
            if (this._isMounted)
                this.setState({
                    expanded: false,
                });
        };
        /** Checks if ExpandableItem is expanded. */
        this.isExpanded = () => {
            return this.state.expanded;
        };
        this._handleOnOutsideClick = (e) => {
            if (!this._ref.current || !(e.target instanceof Node) || this._ref.current.contains(e.target))
                return;
            this.minimize();
            this.props.onExpanded && this.props.onExpanded(false);
        };
        this._handleToolPanelOpenedEvent = () => {
            if (!this._closeOnPanelOpened)
                return;
            this.minimize();
        };
        this._handleClick = () => {
            // istanbul ignore next
            if (!this._isMounted)
                return;
            this.setState((prevState) => {
                const expanded = !prevState.expanded;
                return {
                    expanded,
                };
            }, () => {
                const expanded = this.state.expanded;
                if (expanded) {
                    // Minimize any other list picker that has been opened
                    // This is to mimic Bimium's behavior where pickers only close when other pickers are opened
                    if (lastOpenedPicker && lastOpenedPicker !== this && lastOpenedPicker.isExpanded())
                        lastOpenedPicker.minimize();
                    lastOpenedPicker = this;
                    this._closeOnPanelOpened = false;
                    expanded && InternalFrontstageManager.onToolPanelOpenedEvent.emit();
                    this._closeOnPanelOpened = true;
                }
                this.props.onExpanded && this.props.onExpanded(expanded);
            });
        };
        this.state = {
            expanded: false,
        };
    }
    /** @internal */
    componentDidMount() {
        this._isMounted = true;
        InternalFrontstageManager.onToolPanelOpenedEvent.addListener(this._handleToolPanelOpenedEvent);
    }
    /** @internal */
    componentWillUnmount() {
        this._isMounted = false;
        InternalFrontstageManager.onToolPanelOpenedEvent.addListener(this._handleToolPanelOpenedEvent);
    }
    /** Renders ListPickerBase */
    render() {
        const icon = this.props.iconSpec ? /* istanbul ignore next */ (typeof this.props.iconSpec === "string" ?
            /* istanbul ignore next */ React.createElement(Icon, { iconSpec: this.props.iconSpec }) : React.createElement("i", { className: "icon uifw-item-svg-icon" }, this.props.iconSpec)) :
            React.createElement("i", { className: "icon icon-list" });
        return (React.createElement(ToolbarDragInteractionContext.Consumer, null, (isEnabled) => {
            return (React.createElement(ExpandableItem // eslint-disable-line deprecation/deprecation
            , { ...this.props, hideIndicator: isEnabled, panel: this.getExpandedContent() },
                React.createElement("div", { ref: this._ref },
                    React.createElement(Item // eslint-disable-line deprecation/deprecation
                    , { icon: icon, onClick: this._handleClick, onSizeKnown: this.props.onSizeKnown, title: this.props.title }))));
        }));
    }
    /** Returns the list with the items */
    getExpandedContent() {
        if (!this.state.expanded)
            return undefined;
        const expandSingleSection = () => {
            const populatedContainers = this.props.items.filter((item) => {
                return (item.type === ListItemType.Container && item.children.length !== 0);
            });
            return populatedContainers.length === 1;
        };
        const listItemToElement = (item, itemIndex) => {
            switch (item.type) {
                case ListItemType.Item:
                    return (React.createElement(ListPickerItem, { ...this.props, key: itemIndex.toString(), label: item.name, isActive: item.enabled, onClick: () => { this.props.setEnabled(item, !item.enabled); } }));
                case ListItemType.Separator:
                    return (React.createElement("div", { key: itemIndex.toString(), className: "ListPicker-separator" }));
                case ListItemType.Container:
                    if (item.children.length !== 0) {
                        return (React.createElement(ExpandableSection, { key: itemIndex.toString(), title: item.name, className: "ListPickerInnerContainer", expanded: expandSingleSection() },
                            React.createElement(GroupColumn, null,
                                " ",
                                item.children.map(listItemToElement))));
                    }
                    else {
                        return (React.createElement("div", { key: itemIndex.toString() }));
                    }
                default:
                    return (React.createElement("div", { key: itemIndex.toString() }));
            }
        };
        return (React.createElement(ContainedGroup, { className: "ListPickerContainer", columns: React.createElement(GroupColumn, { className: "ListPicker-column" },
                " ",
                this.props.items.map(listItemToElement)), containFn: containHorizontally, onOutsideClick: this._handleOnOutsideClick, title: this.props.title }));
    }
}
/**
 * List picker toolbar popup item.
 * Used to provide an expandable list of items to enable/disable items.
 * @beta
 */
function ListPickerPopupItem(props) {
    const icon = props.iconSpec ? ( /* istanbul ignore next */typeof props.iconSpec === "string" ? React.createElement(Icon, { iconSpec: props.iconSpec }) :
        React.createElement("i", { className: "icon uifw-item-svg-icon" }, props.iconSpec)) : React.createElement(Icon, { iconSpec: "icon-list" });
    return (React.createElement(ToolbarDragInteractionContext.Consumer, null, (isEnabled) => {
        return React.createElement(PopupItem, { hideIndicator: isEnabled, icon: icon, title: props.title, panel: getListPanel(props) });
    }));
}
/**
 * List Picker that lets the user pick from a list of items to enable/disable
 * It also provides options to enable all, disable all and invert selection
 * @beta
 */
export class ListPicker extends React.Component {
    /** Creates a ListPicker */
    constructor(props) {
        super(props);
        // Handle enabling/disabling the items
        // This will call the this.props.setEnabled function to provide the parent with a chance to process it
        this._setEnabled = (item, enabled) => {
            if (this.isSpecialItem(item)) {
                switch (item.key) {
                    case ListPicker.Key_All: {
                        // istanbul ignore else
                        if (this.props.enableAllFunc)
                            this.props.enableAllFunc();
                        return;
                    }
                    case ListPicker.Key_None: {
                        // istanbul ignore else
                        if (this.props.disableAllFunc)
                            this.props.disableAllFunc();
                        return;
                    }
                    case ListPicker.Key_Invert: {
                        // istanbul ignore else
                        if (this.props.invertFunc)
                            this.props.invertFunc();
                        return;
                    }
                }
            }
            // Call on parent to do processing of the item
            this.props.setEnabled(item, enabled);
        };
    }
    static get Key_All() { return -3; }
    static get Key_None() { return -2; }
    static get Key_Invert() { return -1; }
    static get Key_Separator() { return -4; }
    // Creates an array of items containing the separator and special requests (all, none, invert)
    createItems(items) {
        const newItems = [];
        // Create special buttons (All/None/Invert)
        if (this.props.enableAllFunc) {
            let allEnabled = true;
            items.map((item) => { allEnabled = allEnabled && item.enabled; });
            newItems.push({ key: ListPicker.Key_All, name: UiFramework.translate("pickerButtons.all"), enabled: allEnabled, type: ListItemType.Item });
        }
        if (this.props.disableAllFunc) {
            let allDisabled = false;
            items.map((item) => { allDisabled = allDisabled || item.enabled; });
            newItems.push({ key: ListPicker.Key_None, name: UiFramework.translate("pickerButtons.none"), enabled: !allDisabled, type: ListItemType.Item });
        }
        if (this.props.invertFunc) {
            newItems.push({ key: ListPicker.Key_Invert, name: UiFramework.translate("pickerButtons.invert"), enabled: false, type: ListItemType.Item });
        }
        if (this.props.enableAllFunc || this.props.disableAllFunc || this.props.invertFunc) {
            newItems.push({ key: ListPicker.Key_Separator, name: UiFramework.translate("pickerButtons.separator"), enabled: false, type: ListItemType.Separator });
        }
        // Push items
        items.map((item) => { newItems.push(item); });
        return newItems;
    }
    /**
     * Checks if item is a special item.
     * @param item Item to check
     */
    isSpecialItem(item) {
        return item.key === ListPicker.Key_All || item.key === ListPicker.Key_Invert || item.key === ListPicker.Key_None || item.type !== ListItemType.Item || item.key === ListPicker.Key_Separator;
    }
    /** Renders ListPicker */
    render() {
        return (React.createElement(FrameworkVersionSwitch, { v1: React.createElement(ListPickerBase // eslint-disable-line deprecation/deprecation
            , { ...this.props, title: this.props.title, setEnabled: this._setEnabled, onExpanded: this.props.onExpanded, items: this.createItems(this.props.items), iconSpec: this.props.iconSpec }), v2: React.createElement(ListPickerPopupItem, { ...this.props, title: this.props.title, setEnabled: this._setEnabled, onExpanded: this.props.onExpanded, items: this.createItems(this.props.items), iconSpec: this.props.iconSpec }) }));
    }
}
//# sourceMappingURL=ListPicker.js.map