/*
 * 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.
 */
import * as React from 'react';
import { v4 as uuid } from 'uuid';
import { eventBus, i18n, isWatchable, isTable } from '@kui-shell/core';
import CardSpi from '../spi/Card';
import sameCommand from './util/same';
import { cwd as getCwd } from './Sidecar/BaseSidecar';
import LivePaginatedTable from '../Content/Table/LivePaginatedTable';
import { getBreadcrumbsFromTable } from '../Content/Table/PaginatedTable';
import CircularBuffer from './util/CircularBuffer';
import Breadcrumb from '../spi/Breadcrumb';
const strings = i18n('plugin-client-common');
export default class WatchPane extends React.PureComponent {
    constructor(props) {
        super(props);
        const onResponse = this.onResponse.bind(this);
        eventBus.onScalarResponse(this.props.uuid, onResponse);
        this.state = {
            current: undefined,
            history: undefined
        };
    }
    onResponse(tab, response, _, argvNoOptions, parsedOptions, __, evaluatorOptions, execOptions, command) {
        if (isTable(response) &&
            isWatchable(response) &&
            evaluatorOptions.alwaysViewIn !== 'Terminal' &&
            execOptions.alwaysViewIn !== 'Terminal') {
            this.setState(curState => {
                const cwd = getCwd();
                const existingIdx = curState.history
                    ? curState.history.findIndex(sameCommand(argvNoOptions, parsedOptions, cwd))
                    : -1;
                const current = {
                    key: uuid(),
                    response,
                    argvNoOptions,
                    parsedOptions,
                    command,
                    cwd
                };
                if (current) {
                    this.props.openWatchPane();
                    if (!curState.history) {
                        return {
                            current,
                            history: new CircularBuffer(current, this.capacity())
                        };
                    }
                    else {
                        if (existingIdx === -1) {
                            curState.history.push(current);
                        }
                        else {
                            curState.history.update(existingIdx, current);
                        }
                        return {
                            current,
                            history: curState.history
                        };
                    }
                }
            });
        }
    }
    /** Keep this in sync with WatchPane.scss $num-columns */
    capacity() {
        return 4;
    }
    /** re-execute the command, but display the watch result in terminal */
    watchInTerminal(command) {
        this.props.tab.REPL.pexec(command, { alwaysViewIn: 'Terminal' });
    }
    /** `Card Actions`, will be rendred as `Dropdown` */
    actions(history, watcherIdx) {
        const watchInTerminal = {
            label: strings('Show as table'),
            handler: this.watchInTerminal.bind(this, history.command)
        };
        const stopWatching = {
            label: strings('Stop watching'),
            handler: this.clearSubPane.bind(this, history.response, watcherIdx)
        };
        return [watchInTerminal, stopWatching];
    }
    /** render subpane header as Breadcrumb */
    header(response, idx) {
        const prefixBreadcrumbs = [{ label: `Watcher ${idx + 1}` }];
        const breadcrumbs = getBreadcrumbsFromTable(response, prefixBreadcrumbs);
        return React.createElement(Breadcrumb, { repl: this.props.tab.REPL, breadcrumbs: breadcrumbs.length > 0 && breadcrumbs });
    }
    /** abort the watchable job and clear the watch pane */
    clearSubPane(response, idx) {
        // abort the watchable job
        response.watch.abort();
        // remove the history entry from circular buffer
        this.state.history.popAt(idx);
        // force re-rendering
        this.forceUpdate();
        // remove the watch pane if there's no watcher
        if (!this.state.history || this.state.history.length === 0) {
            this.props.closeWatchPane();
        }
    }
    render() {
        return (React.createElement("div", { className: "kui--watch-pane" }, this.state.history &&
            this.state.history.length !== 0 &&
            Array(this.capacity())
                .fill(undefined)
                .map((_, idx) => {
                const history = this.state.history.peekAt(idx);
                return (React.createElement(CardSpi, { className: `kui--card kui--screenshotable kui--card-${idx + 1}`, actions: history && this.actions(history, idx), header: history && this.header(history.response, idx), key: history ? history.key : idx }, history && (React.createElement("div", { className: "kui--sub-card" },
                    React.createElement(LivePaginatedTable, { tab: this.props.tab, repl: this.props.tab.REPL, response: history.response, asGrid: true, title: false, toolbars: false, paginate: false, onRender: () => false })))));
            })));
    }
}
//# sourceMappingURL=WatchPane.js.map