"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = renderCell;
exports.onClickForCell = onClickForCell;
var _debug = _interopRequireDefault(require("debug"));
var _react = _interopRequireDefault(require("react"));
var _prettyMs = _interopRequireDefault(require("pretty-ms"));
var _TableComposable = require("@patternfly/react-table/dist/esm/components/TableComposable");
var _Capabilities = require("@kui-shell/core/mdist/api/Capabilities");
var _Exec = require("@kui-shell/core/mdist/api/Exec");
var _Icons = _interopRequireDefault(require("../../spi/Icons"));
var _Tooltip = _interopRequireDefault(require("../../spi/Tooltip"));
var _Tooltip2 = _interopRequireWildcard(require("./Tooltip"));
var _ErrorCell = _interopRequireDefault(require("./ErrorCell"));
var _selection = _interopRequireDefault(require("../../../util/selection"));
var _MutabilityContext = require("../../Client/MutabilityContext");
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.
 */
var __awaiter = void 0 && (void 0).__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());
  });
};
const Markdown = _react.default.lazy(() => Promise.resolve().then(() => require('../Markdown')));
const debug = (0, _debug.default)('plugin-client-common/Content/Table/TableCell');
function XOR(a, b) {
  return (a || b) && !(a && b);
}
/**
 * Generate an onclick handler for a cell
 *
 */
function onClickForCell(row, tab, repl, cell, opts, mutability) {
  const {
    selectRow = () => undefined
  } = opts || {};
  // precedence order of drilldownTo protocol, with a default to drill down to a side split
  const drilldownTo = cell && cell.drilldownTo || row.drilldownTo || opts && opts.drilldownTo || 'side-split';
  let handler = cell && cell.onclick ? cell.onclick : row.onclick;
  if (handler === false) {
    return () => handler;
  } else if (typeof handler === 'function') {
    return (0, _selection.default)(evt => {
      evt.stopPropagation();
      selectRow();
      handler();
      return false;
    });
  } else if (handler) {
    const opts = {
      tab
    };
    if (!row.onclickExec || row.onclickExec === 'pexec') {
      return (0, _selection.default)(evt => __awaiter(this, void 0, void 0, function* () {
        evt.stopPropagation();
        selectRow();
        if (mutability && !mutability.executable && row.onclickIdempotent && row.onclickPrefetch) {
          // we have prefetched content! and this client doesn't allow command execution, so use it
          opts.masquerade = row.onclick;
          opts.data = row.onclickPrefetch;
          handler = 'replay-content';
          debug('Implementing table cell drilldown with replayed content', row.onclick);
        }
        if (drilldownTo === 'side-split' && !XOR(evt.metaKey, !!process.env.KUI_SPLIT_DRILLDOWN)) {
          (0, _Exec.pexecInCurrentTab)(`split --ifnot is-split --cmdline "${handler}"`, undefined, false, true, undefined, {
            masquerade: opts.masquerade,
            data: opts.data
          });
        } else if (!(0, _Capabilities.isHeadless)() && drilldownTo === 'new-window') {
          const {
            ipcRenderer
          } = yield Promise.resolve().then(() => require('electron'));
          ipcRenderer.send('synchronous-message', JSON.stringify({
            operation: 'new-window',
            argv: (0, _Exec.split)(handler)
          }));
        } else {
          repl.pexec(handler, opts);
        }
        return false;
      }));
    } else {
      return (0, _selection.default)(evt => {
        evt.stopPropagation();
        selectRow();
        repl.qexec(handler, undefined, undefined, {
          tab
        });
        return false;
      });
    }
  }
}
/**
 * Render a TableCell part
 *
 */
function renderCell(table, kuiRow, justUpdated, tab, repl) {
  return function KuiTableCell(key, value, tag, outerCSS, css, onclick, cidx) {
    // className for the td
    const cellClassName = cidx === 0 ? 'entity-name ' + (outerCSS || '') : (/NAME/i.test(key) ? 'kui--entity-name-secondary ' : /STATUS/i.test(key) ? 'kui--status-cell' : '') + (outerCSS || '');
    const outerClassName = 'display-inline-block cell-inner ' + (css || '') + (onclick ? ' clickable' : '');
    // the text value of the cell
    const valueDom = cidx > 0 && kuiRow.attributes[cidx - 1] && kuiRow.attributes[cidx - 1].valueDom;
    const title = (cidx - 1 === table.durationColumnIdx || cidx - 1 === table.coldStartColumnIdx || cidx - 1 === table.queueingDelayColumnIdx) && value ? (0, _prettyMs.default)(parseInt(value, 10)) : value;
    const innerText = valueDom || title;
    const innerSpan = _react.default.createElement("span", {
      className: "kui--cell-inner-text"
    }, cidx === 0 && kuiRow.fontawesome === 'fas fa-check' ? _react.default.createElement(_Icons.default, {
      icon: "Checkmark"
    }) : table.markdown ? _react.default.createElement(Markdown, {
      nested: true,
      source: title
    }) : innerText);
    const innerSpanWithTooltip = cidx === 0 && table.title ? _react.default.createElement(_Tooltip.default, Object.assign({
      markdown: (0, _Tooltip2.default)(table.title, kuiRow.name)
    }, _Tooltip2.tooltipProps), innerSpan) : innerSpan;
    const {
      attributes = []
    } = kuiRow;
    // re: OBJECT, see https://github.com/IBM/kui/issues/6831
    return _react.default.createElement(_MutabilityContext.MutabilityContext.Consumer, {
      key: cidx
    }, mutability => _react.default.createElement(_TableComposable.Td, {
      className: cellClassName,
      modifier: /OBJECT/i.test(key) || /MESSAGE/i.test(key) ? 'wrap' : /STATUS/i.test(key) ? 'nowrap' : !/NAME|NAMESPACE/i.test(key) ? 'fitContent' : undefined
    }, _react.default.createElement("div", {
      "data-key": key,
      "data-value": value,
      "data-tag": tag,
      className: outerClassName,
      onClick: onclick ? onClickForCell(kuiRow, tab, repl, attributes[cidx - 1], table, mutability) : undefined
    }, tag === 'badge' && _react.default.createElement(_Tooltip.default, {
      content: title
    }, _react.default.createElement("span", {
      key: css /* force restart of animation if color changes */,
      className: css || 'kui--status-unknown',
      "data-tag": "badge-circle",
      "data-just-updated": justUpdated || undefined
    }, /red-background/.test(css) ? _react.default.createElement(_ErrorCell.default, null) : undefined)), innerSpanWithTooltip)));
  };
}