/*
 * Copyright 2021 The Kubernetes Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable react/prop-types, react/display-name */
import React from 'react';
import Slugger from 'github-slugger';
import { EventEmitter } from 'events';
import { Tab, Tabs, TabTitleText } from '@patternfly/react-core/dist/esm/components/Tabs';
import Card from '../../../spi/Card';
import isElementWithProperties from '../isElement';
const activateEvents = new EventEmitter();
export function activateTab(slug, evt) {
    activateEvents.emit(slug, evt);
}
const switchEvents = new EventEmitter();
export function onTabSwitch(uuid, cb) {
    switchEvents.on(uuid, cb);
}
export function offTabSwitch(uuid, cb) {
    switchEvents.off(uuid, cb);
}
function emitTabSwitch(uuid, group, member) {
    switchEvents.emit(uuid, group, member);
}
export const CurrentMarkdownTab = React.createContext({
    activeKey: 0,
    previousActiveKey: undefined
});
export class LinkableTabs extends React.PureComponent {
    constructor(props) {
        super(props);
        this.slugs = new Slugger();
        this.cleaners = [];
        this.onSelect = (_, tabIndex) => {
            const selectedTab = this.props.tabs[tabIndex];
            emitTabSwitch(this.props.uuid, LinkableTabs.group(this.props), this.member(selectedTab));
            // props.choices.set(LinkableTabs.group(this.props), selectedTab.props.title)
            this.setState(curState => ({
                activeKey: tabIndex,
                previousActiveKey: curState.activeKey
            }));
        };
        this.state = {
            activeKey: LinkableTabs.findActiveKey(props),
            previousActiveKey: undefined
        };
    }
    static findActiveKey(props) {
        const activeTitle = props.choices.getKey(LinkableTabs.group(props));
        const idx = LinkableTabs.findTabIndex(props, activeTitle);
        return idx < 0 ? 0 : idx;
    }
    static findTabIndex(props, title) {
        // Note the case-insensitive comparison
        return props.tabs.findIndex(_ => _.props.title.localeCompare(title, undefined, { sensitivity: 'accent' }) === 0);
    }
    initEvents() {
        ;
        (this.props.tabs || [])
            .map(_ => this.slugs.slug(_.props.title))
            .forEach((slug, activeKey) => {
            const onActivate = (evt) => {
                this.setState(curState => ({ activeKey, previousActiveKey: curState.activeKey }));
                if (evt) {
                    // prevent default interpretation of onClick for the href
                    evt.preventDefault();
                }
            };
            activateEvents.on(slug, onActivate);
            this.cleaners.push(() => activateEvents.off(`/markdown/tabs/activate/${slug}`, onActivate));
        });
    }
    componentDidMount() {
        this.initEvents();
    }
    componentWillUnmount() {
        this.cleaners.forEach(_ => _());
    }
    static group(props) {
        return props['data-kui-choice-group'];
    }
    member(tab) {
        return tab.props['data-kui-tab-index'];
    }
    render() {
        return this.asTabs();
    }
    get isSecondary() {
        return this.props.depth > 0;
    }
    /** Render as a Tabs UI */
    asTabs() {
        return (React.createElement(Tabs, { className: "kui--markdown-tabs paragraph", activeKey: this.state.activeKey, onSelect: this.onSelect, mountOnEnter: true, "data-depth": this.props.depth, isSecondary: this.isSecondary }, (this.props.tabs || []).map((_, idx) => (React.createElement(Tab, { key: idx, eventKey: idx, "data-depth": this.props.depth, "data-title": _.props.title, className: "kui--markdown-tab", title: React.createElement(TabTitleText, null, _.props.title) },
            React.createElement(Card, { className: "kui--markdown-tab-card" },
                React.createElement(CurrentMarkdownTab.Provider, { value: this.state }, _.props && _.props.children)))))));
        // re: the <React.Fragment> wrapper around props.tabs; this is
        // to avoid Card's PatternFly impl creating a separate Markdown
        // component for every child. We know here that all of the children are part
        // of the same contiguous stretch of text.
    }
}
export function getTabsDepth(props) {
    return typeof props.depth === 'number' ? props.depth : parseInt(props.depth.toString(), 10);
}
export function getTabTitle(child) {
    return (isElementWithProperties(child) && child.properties.title) || '';
}
export function isTabs(props) {
    return typeof props['data-kui-choice-group'] === 'string';
}
export default function tabbedWrapper(uuid, choices) {
    return function tabbed(props) {
        // isSecondary={parseInt(props.depth, 10) > 0}
        return (React.createElement(LinkableTabs, { uuid: uuid, choices: choices, depth: parseInt(props.depth, 10), "data-kui-choice-group": props['data-kui-choice-group'], tabs: props.children }));
    };
}
//# sourceMappingURL=tabbed.js.map