/*
 * 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 { TableStyle, i18n } from '@kui-shell/core';
import * as React from 'react';
import { DataTable, TableContainer, Table } from 'carbon-components-react';
import sortRow from './sort';
import Card from '../../spi/Card';
import renderBody from './TableBody';
import renderHeader from './TableHeader';
import Toolbar from './Toolbar';
import Grid, { findGridableColumn } from './Grid';
import kui2carbon from './kui2carbon';
/** carbon styling */
import 'carbon-components/scss/components/data-table/_data-table-core.scss';
import 'carbon-components/scss/components/data-table/_data-table-sort.scss';
/** hack (see comments in file) */
import '../../../../web/scss/components/Table/hack-select.scss';
/** import the kui theme alignment */
import '../../../../web/scss/components/Table/carbon-kui-theme-alignment.scss';
import '../../../../web/css/static/ToolbarButton.scss';
import '../../../../web/scss/components/Table/Toolbar.scss';
const strings = i18n('plugin-client-common');
export function getBreadcrumbsFromTable(response, prefixBreadcrumbs) {
    const titleBreadcrumb = response.title
        ? [{ label: response.title, className: 'kui--data-table-title', isCurrentPage: true }]
        : [];
    const _responseCrumbs = typeof response.breadcrumbs === 'function' ? response.breadcrumbs() : response.breadcrumbs;
    const responseCrumbs = !_responseCrumbs
        ? []
        : _responseCrumbs.map(_ => Object.assign({}, _, { className: 'kui--secondary-breadcrumb' }));
    const breadcrumbs = (prefixBreadcrumbs || []).concat(responseCrumbs).concat(titleBreadcrumb);
    return breadcrumbs;
}
/**
 * A DataTable/Pagination pair
 *
 */
export default class PaginatedTable extends React.PureComponent {
    constructor(props) {
        super(props);
        this.defaultPageSize = props.pageSize || 10;
        try {
            // assemble the data model
            const { headers, rows } = kui2carbon(this.props.response);
            this.state = {
                headers,
                rows,
                asGrid: this.props.asGrid,
                page: 1,
                pageSize: this.defaultPageSize
            };
        }
        catch (err) {
            console.error('Internal error preparing PaginatedTable', err);
        }
    }
    topToolbar() {
        // 1) If we started as a table, and are now a grid, then show
        // "Status Grid", otherwise:
        // 2) only for client w/o disableTableTitle, show a breadcrumb
        const breadcrumbs = !this.props.asGrid && this.state.asGrid
            ? [{ label: strings('Status Grid') }]
            : !this.props.asGrid && !this.props.title
                ? []
                : getBreadcrumbsFromTable(this.props.response, this.props.prefixBreadcrumbs);
        if (breadcrumbs.length > 0) {
            return React.createElement(Toolbar, { className: "kui--data-table-toolbar-top", breadcrumbs: breadcrumbs.length > 0 && breadcrumbs });
        }
    }
    isPaginated() {
        return false;
        /**
         * return (
         * this.props.paginate !== undefined &&
         * this.props.paginate !== false &&
         * !this.state.asGrid &&
         * (this.props.paginate === true || this.state.rows.length > this.props.paginate)
         * )
         */
    }
    bottomToolbar() {
        const gridableColumn = findGridableColumn(this.props.response);
        return (this.props.toolbars &&
            (this.isPaginated() || gridableColumn >= 0) && (React.createElement(Toolbar, { framed: true, className: "kui--data-table-toolbar-bottom", asGrid: this.state.asGrid, gridableColumn: gridableColumn, setAsGrid: (asGrid) => this.setState({ asGrid }), paginate: this.isPaginated(), setPage: (page) => this.setState({ page }), page: this.state.page, totalItems: this.state.rows.length, pageSize: this.state.pageSize })));
    }
    grid(visibleRows) {
        return (React.createElement(Grid, { tab: this.props.tab, repl: this.props.repl, response: this.props.response, visibleRows: visibleRows, justUpdated: this.justUpdatedMap() }));
    }
    justUpdatedMap() {
        return this.state.rows.reduce((M, _) => {
            if (_.justUpdated)
                M[_.rowKey] = true;
            return M;
        }, {});
    }
    table() {
        const { tab, repl, response } = this.props;
        const { headers, rows, page } = this.state;
        const dataTable = (visibleRows, offset = 0) => (React.createElement(React.Fragment, null,
            React.createElement(DataTable, { rows: visibleRows, headers: headers, isSortable: true, sortRow: sortRow, render: renderOpts => (React.createElement(TableContainer, { className: (this.props.title ? 'kui--data-table-container-with-toolbars' : '') +
                        (this.props.response.title || this.props.response.breadcrumbs
                            ? ' kui--data-table-container-with-title'
                            : '') },
                    React.createElement(Table, { size: this.props.response.style === TableStyle.Heavy
                            ? 'tall'
                            : this.props.response.style === TableStyle.Medium
                                ? 'short'
                                : 'short' },
                        response.header && renderHeader(response.header, renderOpts),
                        renderBody(response.body, this.justUpdatedMap(), renderOpts, tab, repl, offset)))) })));
        const paginated = this.isPaginated();
        return dataTable(!paginated ? rows : rows.slice((page - 1) * this.state.pageSize, page * this.state.pageSize), !paginated ? 0 : (page - 1) * this.state.pageSize);
    }
    content(includeToolbars = false) {
        return (React.createElement(React.Fragment, null,
            includeToolbars && this.topToolbar(),
            this.state.asGrid ? this.grid(this.state.rows) : this.table(),
            includeToolbars && this.bottomToolbar()));
    }
    render() {
        if (!this.state) {
            return React.createElement("div", { className: "oops" }, "Internal Error");
        }
        else {
            const className = 'kui--data-table-wrapper kui--screenshotable' + (this.state.asGrid ? ' kui--data-table-as-grid' : '');
            return this.props.response.style === TableStyle.Light || this.props.asGrid ? (React.createElement("div", { className: className }, this.content(true))) : (React.createElement(Card, { header: this.topToolbar(), footer: this.bottomToolbar(), className: className }, this.content()));
        }
    }
}
//# sourceMappingURL=PaginatedTable.js.map