import * as tslib_1 from "tslib";
import * as React from 'react';
import { BaseComponent, KeyCodes, getId, getNativeProps, divProperties, classNamesFunction, warn } from '../../Utilities';
import { CommandButton } from '../../Button';
import { FocusZone, FocusZoneDirection } from '../../FocusZone';
import { PivotItem } from './PivotItem';
import { PivotLinkFormat } from './Pivot.types';
import { PivotLinkSize } from './Pivot.types';
import { Icon } from '../../Icon';
var getClassNames = classNamesFunction();
var PivotItemType = React.createElement(PivotItem, null).type;
/**
 *  Usage:
 *
 *     <Pivot>
 *       <PivotItem headerText="Foo">
 *         <Label>Pivot #1</Label>
 *       </PivotItem>
 *       <PivotItem headerText="Bar">
 *         <Label>Pivot #2</Label>
 *       </PivotItem>
 *       <PivotItem headerText="Bas">
 *         <Label>Pivot #3</Label>
 *       </PivotItem>
 *     </Pivot>
 */
var PivotBase = /** @class */ (function (_super) {
    tslib_1.__extends(PivotBase, _super);
    function PivotBase(props) {
        var _this = _super.call(this, props) || this;
        _this._focusZone = React.createRef();
        _this._renderPivotLink = function (link) {
            var itemKey = link.itemKey, headerButtonProps = link.headerButtonProps;
            var tabId = _this._keyToTabIds[itemKey];
            var onRenderItemLink = link.onRenderItemLink;
            var linkContent;
            var isSelected = _this.state.selectedKey === itemKey;
            if (onRenderItemLink) {
                linkContent = onRenderItemLink(link, _this._renderLinkContent);
            }
            else {
                linkContent = _this._renderLinkContent(link);
            }
            return (React.createElement(CommandButton, tslib_1.__assign({}, headerButtonProps, { id: tabId, key: itemKey, className: isSelected ? _this._classNames.linkIsSelected : _this._classNames.link, onClick: _this._onLinkClick.bind(_this, itemKey), onKeyPress: _this._onKeyPress.bind(_this, itemKey), ariaLabel: link.ariaLabel, role: "tab", "aria-selected": isSelected, name: link.headerText, keytipProps: link.keytipProps }), linkContent));
        };
        _this._renderLinkContent = function (link) {
            var itemCount = link.itemCount, itemIcon = link.itemIcon, headerText = link.headerText;
            var classNames = _this._classNames;
            return (React.createElement("span", { className: classNames.linkContent },
                itemIcon !== undefined && (React.createElement("span", { className: classNames.icon },
                    React.createElement(Icon, { iconName: itemIcon }))),
                headerText !== undefined && React.createElement("span", { className: classNames.text },
                    " ",
                    link.headerText),
                itemCount !== undefined && React.createElement("span", { className: classNames.count },
                    " (",
                    itemCount,
                    ")")));
        };
        /**
         * Renders the current Pivot Item
         */
        _this._renderPivotItem = function () {
            var itemKey = _this.state.selectedKey;
            if (_this.props.headersOnly || !itemKey) {
                return null;
            }
            var index = _this._keyToIndexMapping[itemKey];
            var selectedTabId = _this._keyToTabIds[itemKey];
            return (React.createElement("div", { role: "tabpanel", "aria-labelledby": selectedTabId }, React.Children.toArray(_this.props.children)[index]));
        };
        _this._warnDeprecations({
            initialSelectedKey: 'defaultSelectedKey',
            initialSelectedIndex: 'defaultSelectedIndex'
        });
        _this._pivotId = getId('Pivot');
        var links = _this._getPivotLinks(props);
        var _a = props.defaultSelectedKey, defaultSelectedKey = _a === void 0 ? props.initialSelectedKey : _a, _b = props.defaultSelectedIndex, defaultSelectedIndex = _b === void 0 ? props.initialSelectedIndex : _b, selectedKeyFromProps = props.selectedKey;
        var selectedKey;
        if (defaultSelectedKey) {
            selectedKey = defaultSelectedKey;
        }
        else if (typeof defaultSelectedIndex === 'number') {
            selectedKey = links[defaultSelectedIndex].itemKey;
        }
        else if (selectedKeyFromProps) {
            selectedKey = selectedKeyFromProps;
        }
        else if (links.length) {
            selectedKey = links[0].itemKey;
        }
        _this.state = {
            links: links,
            selectedKey: selectedKey
        };
        return _this;
    }
    PivotBase.prototype.componentWillReceiveProps = function (nextProps) {
        var _this = this;
        var links = this._getPivotLinks(nextProps);
        this.setState(function (prevState) {
            var selectedKey;
            if (_this._isKeyValid(nextProps.selectedKey)) {
                selectedKey = nextProps.selectedKey;
            }
            else if (_this._isKeyValid(prevState.selectedKey)) {
                selectedKey = prevState.selectedKey;
            }
            else if (links.length) {
                selectedKey = links[0].itemKey;
            }
            return {
                links: links,
                selectedKey: selectedKey
            };
        });
    };
    /**
     * Sets focus to the first pivot tab.
     */
    PivotBase.prototype.focus = function () {
        if (this._focusZone.current) {
            this._focusZone.current.focus();
        }
    };
    PivotBase.prototype.render = function () {
        var divProps = getNativeProps(this.props, divProperties);
        this._classNames = this._getClassNames(this.props);
        return (React.createElement("div", tslib_1.__assign({}, divProps),
            this._renderPivotLinks(),
            this._renderPivotItem()));
    };
    /**
     * Renders the set of links to route between pivots
     */
    PivotBase.prototype._renderPivotLinks = function () {
        var items = this.state.links.map(this._renderPivotLink);
        return (React.createElement(FocusZone, { componentRef: this._focusZone, direction: FocusZoneDirection.horizontal },
            React.createElement("div", { className: this._classNames.root, role: "tablist" }, items)));
    };
    /**
     * Gets the set of PivotLinks as arrary of IPivotItemProps
     * The set of Links is determined by child components of type PivotItem
     */
    PivotBase.prototype._getPivotLinks = function (props) {
        var _this = this;
        var links = [];
        this._keyToIndexMapping = {};
        this._keyToTabIds = {};
        React.Children.map(props.children, function (child, index) {
            if (typeof child === 'object' && child.type === PivotItemType) {
                var pivotItem = child;
                var _a = pivotItem.props, linkText = _a.linkText, pivotItemProps = tslib_1.__rest(_a, ["linkText"]);
                var itemKey = pivotItem.props.itemKey || index.toString();
                links.push(tslib_1.__assign({ 
                    // Use linkText (deprecated) if headerText is not provided
                    headerText: linkText }, pivotItemProps, { itemKey: itemKey }));
                _this._keyToIndexMapping[itemKey] = index;
                _this._keyToTabIds[itemKey] = _this._getTabId(itemKey, index);
            }
            else {
                warn('The children of a Pivot component must be of type PivotItem to be rendered.');
            }
        });
        return links;
    };
    /**
     * Generates the Id for the tab button.
     */
    PivotBase.prototype._getTabId = function (itemKey, index) {
        if (this.props.getTabId) {
            return this.props.getTabId(itemKey, index);
        }
        return this._pivotId + ("-Tab" + index);
    };
    /**
     * whether the key exists in the pivot items.
     */
    PivotBase.prototype._isKeyValid = function (itemKey) {
        return itemKey !== undefined && this._keyToIndexMapping[itemKey] !== undefined;
    };
    /**
     * Handles the onClick event on PivotLinks
     */
    PivotBase.prototype._onLinkClick = function (itemKey, ev) {
        ev.preventDefault();
        this._updateSelectedItem(itemKey, ev);
    };
    /**
     * Handle the onKeyPress eventon the PivotLinks
     */
    PivotBase.prototype._onKeyPress = function (itemKey, ev) {
        if (ev.which === KeyCodes.enter) {
            ev.preventDefault();
            this._updateSelectedItem(itemKey);
        }
    };
    /**
     * Updates the state with the new selected index
     */
    PivotBase.prototype._updateSelectedItem = function (itemKey, ev) {
        this.setState({
            selectedKey: itemKey
        });
        if (this.props.onLinkClick && this._keyToIndexMapping[itemKey] >= 0) {
            var index = this._keyToIndexMapping[itemKey];
            // React.Element<any> cannot directly convert to PivotItem.
            var item = React.Children.toArray(this.props.children)[index];
            if (typeof item === 'object' && item.type === PivotItemType) {
                this.props.onLinkClick(item, ev);
            }
        }
    };
    PivotBase.prototype._getClassNames = function (props) {
        var theme = props.theme;
        var rootIsLarge = props.linkSize === PivotLinkSize.large;
        var rootIsTabs = props.linkFormat === PivotLinkFormat.tabs;
        return getClassNames(props.styles, {
            theme: theme,
            rootIsLarge: rootIsLarge,
            rootIsTabs: rootIsTabs
        });
    };
    return PivotBase;
}(BaseComponent));
export { PivotBase };
//# sourceMappingURL=Pivot.base.js.map