"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getBreadcrumbsFromTable = getBreadcrumbsFromTable;
exports.default = void 0;

var _core = require("@kui-shell/core");

var React = _interopRequireWildcard(require("react"));

var _carbonComponentsReact = require("carbon-components-react");

var _sort = _interopRequireDefault(require("./sort"));

var _Card = _interopRequireDefault(require("../../spi/Card"));

var _TableBody = _interopRequireDefault(require("./TableBody"));

var _TableHeader = _interopRequireDefault(require("./TableHeader"));

var _Toolbar = _interopRequireDefault(require("./Toolbar"));

var _Grid = _interopRequireWildcard(require("./Grid"));

var _kui2carbon = _interopRequireDefault(require("./kui2carbon"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

/*
 * 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.
 */
const strings = (0, _core.i18n)('plugin-client-common');

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
 *
 */


class PaginatedTable extends React.PureComponent {
  constructor(props) {
    super(props);
    this.defaultPageSize = props.pageSize || 10;

    try {
      // assemble the data model
      const {
        headers,
        rows
      } = (0, _kui2carbon.default)(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.default, {
        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 = (0, _Grid.findGridableColumn)(this.props.response);
    return this.props.toolbars && (this.isPaginated() || gridableColumn >= 0) && React.createElement(_Toolbar.default, {
      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.default, {
      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(_carbonComponentsReact.DataTable, {
      rows: visibleRows,
      headers: headers,
      isSortable: true,
      sortRow: _sort.default,
      render: renderOpts => React.createElement(_carbonComponentsReact.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(_carbonComponentsReact.Table, {
        size: this.props.response.style === _core.TableStyle.Heavy ? 'tall' : this.props.response.style === _core.TableStyle.Medium ? 'short' : 'short'
      }, response.header && (0, _TableHeader.default)(response.header, renderOpts), (0, _TableBody.default)(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 === _core.TableStyle.Light || this.props.asGrid ? React.createElement("div", {
        className: className
      }, this.content(true)) : React.createElement(_Card.default, {
        header: this.topToolbar(),
        footer: this.bottomToolbar(),
        className: className
      }, this.content());
    }
  }

}

exports.default = PaginatedTable;