"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findGridableColumn = exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _ErrorCell = _interopRequireDefault(require("./ErrorCell"));
var _Tooltip = _interopRequireDefault(require("../../spi/Tooltip"));
var _TableCell = require("./TableCell");
var _Coloring = _interopRequireDefault(require("./Coloring"));
var _Tooltip2 = _interopRequireWildcard(require("./Tooltip"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
 * Copyright 2020 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.
 */

const Markdown = _react.default.lazy(() => Promise.resolve().then(() => require('../Markdown')));
const findGridableColumn = response => {
  // why the or part? well, if the controller hasn't specified a
  // colorBy, and we have a durationColumnIdx but *not* a
  // statusColumnIdx, then use duration as the default
  const colorByDuration = response.colorBy === 'duration' || response.statusColumnIdx === undefined;
  return colorByDuration && response.durationColumnIdx >= 0 ? response.durationColumnIdx : response.statusColumnIdx !== undefined ? response.statusColumnIdx : response.body[0] && response.header ? response.header.attributes.findIndex(cell => /STATUS|REASON/i.test(cell.key)) : -1;
};
/**
 * A Grid table
 *
 */
exports.findGridableColumn = findGridableColumn;
class Grid extends _react.default.PureComponent {
  constructor(props) {
    super(props);
    this.state = Grid.getDerivedStateFromProps(props);
  }
  static getDerivedStateFromProps(props) {
    return {
      coloring: findGridableColumn(props.response) >= 0 ? new _Coloring.default(props.response) : undefined
    };
  }
  durationCss(row, isError) {
    const {
      durationColumnIdx
    } = this.props.response;
    if (row.attributes[durationColumnIdx]) {
      const duration = parseInt(row.attributes[durationColumnIdx].value, 10);
      return this.state.coloring.durationCss(duration, isError);
    } else {
      return '';
    }
  }
  render() {
    const gridableColumn = findGridableColumn(this.props.response);
    if (gridableColumn < 0) {
      return this.renderWithNames();
    } else {
      return this.renderWithBadges(gridableColumn);
    }
  }
  /** Render as a grid of names */
  renderWithNames() {
    const longest = this.props.response.body.reduce((max, row) => max.length < row.name.length ? row.name : max, '');
    let ex = 0;
    let em = 2; // <-- for good measure
    for (let idx = 0; idx < longest.length; idx++) {
      const char = longest.charAt(idx);
      if (char === 'm') em++;else ex++;
    }
    return _react.default.createElement("div", {
      className: "grid-layout",
      style: {
        gridTemplateColumns: `repeat(auto-fill, minmax(calc(${ex}ex + ${em}em), auto))`
      }
    }, this.props.response.body.map(_ => _react.default.createElement("div", {
      key: _.name,
      "data-name": _.name,
      className: _.css
    }, _react.default.createElement("span", {
      className: _.onclick && 'clickable',
      onClick: (0, _TableCell.onClickForCell)(_, this.props.tab, this.props.repl, _.onclick, this.props.response)
    }, this.props.response.markdown ? _react.default.createElement(Markdown, {
      nested: true,
      source: _.name
    }) : _.name))));
  }
  /** Render as a grid of [] square/circle badges */
  renderWithBadges(gridableColumn) {
    const {
      tab,
      repl,
      response,
      visibleRows
    } = this.props;
    const nCells = visibleRows.length;
    const nColumns = Math.ceil(Math.sqrt(nCells));
    const style = {
      gridTemplateColumns: `repeat(${nColumns}, 1.25rem)`
    };
    const colorByDuration = response.colorBy === 'duration' || !response.colorBy && response.durationColumnIdx >= 0;
    return _react.default.createElement("div", {
      className: "kui--table-like-wrapper kui--data-table-as-grid",
      style: style
    }, response.body.map((kuiRow, kidx) => {
      const badgeCell = gridableColumn !== -1 && kuiRow.attributes[gridableColumn];
      const statusCss = badgeCell && badgeCell.css && badgeCell.css.trim() || 'kui--status-unknown';
      const isError = /red-background/.test(statusCss);
      const css = colorByDuration ? this.durationCss(kuiRow, isError) : statusCss;
      // cell label, to be displayed inside of the grid cell
      const label = _react.default.createElement("span", {
        className: "kui--grid-cell-label"
      }, kuiRow.name.slice(0, 2));
      const props = {
        key: css,
        'data-tag': 'badge-circle',
        'data-color-by': colorByDuration ? 'duration' : 'status',
        'data-just-updated': this.props.justUpdated[kuiRow.rowKey || kuiRow.name],
        className: css,
        onClick: (0, _TableCell.onClickForCell)(kuiRow, tab, repl, kuiRow.attributes.find(_ => _.onclick), this.props.response)
      };
      const title = (0, _Tooltip2.default)(this.props.response.title, kuiRow.name, badgeCell ? badgeCell.value : undefined);
      const classNameForCell = 'kui--grid-cell ' + (kuiRow.rowCSS ? typeof kuiRow.rowCSS === 'string' ? kuiRow.rowCSS : kuiRow.rowCSS.join(' ') : '');
      return _react.default.createElement("span", {
        key: kidx,
        "data-tag": "badge",
        "data-entity-name": kuiRow.name,
        className: classNameForCell
      }, _react.default.createElement(_Tooltip.default, Object.assign({
        markdown: title
      }, _Tooltip2.tooltipProps), _react.default.createElement("span", Object.assign({}, props), /red-background/.test(css) ? _react.default.createElement(_ErrorCell.default, null) : label)));
    }));
  }
}
exports.default = Grid;