/*
 * Copyright 2020 IBM Corporation
 *
 * 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.
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import * as React from 'react';
import { i18n, eventBus, eventChannelUnsafe, ExecType, getDefaultTheme, getPersistedThemeChoice, findThemeByName } from '@kui-shell/core';
import { HeaderMenuItem } from 'carbon-components-react';
import Icons from '../../spi/Icons';
const strings = i18n('plugin-core-support');
const strings2 = i18n('plugin-client-common');
export default class Tab extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            title: strings('Tab'),
            processing: false,
            isFreshlyCreated: true,
            topTabNames: props.topTabNames || 'command'
        };
        if (!props.topTabNames) {
            setTimeout(() => __awaiter(this, void 0, void 0, function* () {
                const { theme } = yield findThemeByName((yield getPersistedThemeChoice()) || (yield getDefaultTheme()));
                if (theme.topTabNames) {
                    this.setState({
                        topTabNames: theme.topTabNames
                    });
                }
            }));
        }
        this.addCommandEvaluationListeners();
    }
    componentWillUnmount() {
        this.removeCommandEvaluationListeners();
    }
    removeCommandEvaluationListeners() {
        eventBus.offCommandStart(this.props.uuid, this.onCommandStart);
        eventBus.offCommandComplete(this.props.uuid, this.onCommandStart);
        eventChannelUnsafe.off('/theme/change', this.onThemeChange);
    }
    /**
     * Register any command evaluation listeners, i.e. when the REPL finishes evaluating a command.
     *
     */
    addCommandEvaluationListeners() {
        this.onCommandComplete = (event) => {
            if (this.props.uuid === event.tab.state.uuid) {
                if (event.execType !== undefined && event.execType !== ExecType.Nested && event.route) {
                    // ignore nested, which means one plugin calling another
                    this.setState({ processing: false });
                }
                this.setState({ processing: false });
            }
        };
        this.onCommandStart = (event) => {
            if (this.props.uuid === event.tab.state.uuid) {
                if (event.execType !== undefined && event.execType !== ExecType.Nested && event.route) {
                    // ignore nested, which means one plugin calling another
                    // debug('got event', event)
                    if (event.route !== undefined &&
                        !event.route.match(/^\/(tab|getting\/started)/) // ignore our own events and help
                    ) {
                        if (this.isUsingCommandName()) {
                            this.setState({ processing: true, title: event.command || this.state.title, isFreshlyCreated: false });
                            return;
                        }
                    }
                    this.setState({ processing: true, isFreshlyCreated: false });
                }
            }
        };
        this.onThemeChange = ({ themeModel }) => {
            this.setState({
                topTabNames: themeModel.topTabNames || 'command'
            });
        };
        eventBus.onCommandStart(this.props.uuid, this.onCommandStart);
        eventBus.onCommandComplete(this.props.uuid, this.onCommandComplete);
        eventChannelUnsafe.on('/theme/change', this.onThemeChange);
    }
    isUsingCommandName() {
        return this.state.topTabNames === 'command'; // && !document.body.classList.contains('kui--alternate')
    }
    render() {
        return (React.createElement(HeaderMenuItem, { href: "#", "data-tab-names": this.state.topTabNames, "data-fresh": this.state.isFreshlyCreated, className: 'kui--tab kui--tab-navigatable' +
                (this.props.active ? ' kui--tab--active' : '') +
                (this.state.processing ? ' processing' : ''), "data-tab-button-index": this.props.idx + 1, "aria-label": "tab", onMouseDown: evt => {
                evt.preventDefault();
                evt.stopPropagation();
            }, onClick: () => {
                this.props.onSwitchTab(this.props.idx);
            } },
            React.createElement("div", { className: "kui--tab--label" },
                this.isUsingCommandName() && this.state.title,
                !this.isUsingCommandName() && React.createElement("span", { className: "kui--tab--label-text" },
                    strings('Tab'),
                    " "),
                !this.isUsingCommandName() && React.createElement("span", { className: "kui--tab--label-index" })),
            this.props.closeable && (React.createElement("div", { className: "kui--tab-close", title: strings2('Close this tab'), onClick: evt => {
                    evt.stopPropagation();
                    evt.preventDefault();
                    this.props.onCloseTab(this.props.idx);
                } },
                React.createElement(Icons, { icon: "WindowClose", focusable: "false", preserveAspectRatio: "xMidYMid meet", "aria-hidden": "true" })))));
    }
}
//# sourceMappingURL=Tab.js.map