"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _core = require("@kui-shell/core");
var _HTMLDom = _interopRequireDefault(require("./HTMLDom"));
var _Table = _interopRequireDefault(require("../Table"));
var _2 = require("../../../");
var _BlockModel = require("../../Views/Terminal/Block/BlockModel");
var _MutabilityContext = require("../../Client/MutabilityContext");
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 Ansi = _react.default.lazy(() => Promise.resolve().then(() => require('./Ansi')));
const Commentary = _react.default.lazy(() => Promise.resolve().then(() => require('../Commentary')));
// !! DO NOT MAKE LAZY. See https://github.com/IBM/kui/issues/6758
const XtermDom = _react.default.lazy(() => Promise.resolve().then(() => require('./XtermDom')));
const Markdown = _react.default.lazy(() => Promise.resolve().then(() => require('../Markdown')));
const RadioTableSpi = _react.default.lazy(() => Promise.resolve().then(() => require('../../spi/RadioTable')));
const TopNavSidecar = _react.default.lazy(() => Promise.resolve().then(() => require('../../Views/Sidecar/TopNavSidecarV2')));
const LeftNavSidecar = _react.default.lazy(() => Promise.resolve().then(() => require('../../Views/Sidecar/LeftNavSidecarV2')));
const strings = (0, _core.i18n)('plugin-client-common', 'errors');
/**
 * Component that renders a "ScalarResponse", which is a command
 * response that doesn't require any particularly special
 * interpretation or visualization of the inner structure --- i.e. a
 * response that is suitable for rendering directly in the Terminal.
 *
 */
class Scalar extends _react.default.PureComponent {
  constructor(props) {
    super(props);
    this._onRender = this.onRender.bind(this);
    this.state = Scalar.getDerivedStateFromProps();
  }
  static getDerivedStateFromProps() {
    return {
      catastrophicError: undefined
    };
  }
  static getDerivedStateFromError(error) {
    return {
      catastrophicError: error
    };
  }
  componentDidCatch(error, errorInfo) {
    console.error('catastrophic error in Scalar', error, errorInfo);
  }
  onRender(hasContent = true) {
    if (this.props.onRender) {
      setTimeout(() => this.props.onRender(hasContent === 'undefined' ? undefined : hasContent), 0);
    }
  }
  get repl() {
    return this.props.tab ? this.props.tab.REPL : undefined;
  }
  renderResponse(response) {
    const {
      tab
    } = this.props;
    if (typeof response === 'boolean') {
      // !!! intentionally quoted and not false, Output.tsx uses
      // !!! assertHasContent !== undefined
      this.onRender('undefined');
      return _react.default.createElement(_react.default.Fragment, null);
    } else if (typeof response === 'number') {
      this.onRender();
      return _react.default.createElement("pre", null, response);
    } else if ((0, _core.isUsageError)(response)) {
      // hopefully we can do away with this shortly
      this.onRender();
      if (typeof response.raw === 'string') {
        return _react.default.createElement("pre", null, response.raw);
      } else if ((0, _core.isMessageWithUsageModel)(response.raw) || (0, _core.isMessageWithCode)(response.raw)) {
        return _react.default.createElement("pre", null, response.raw.message);
      } else {
        return _react.default.createElement(_HTMLDom.default, {
          content: response.raw
        });
      }
    } else if ((0, _core.isXtermResponse)(response)) {
      this.onRender(response.rows && response.rows.length > 0);
      return _react.default.createElement(XtermDom, {
        response: response
      });
    } else if (Buffer.isBuffer(response) || typeof response === 'string' || (0, _BlockModel.isError)(response)) {
      const message = (0, _BlockModel.isError)(response) ? response.message : response.toString();
      // Markdown interprets escapes, so we need to double-escape
      if (message[0] === '\u001b') {
        return _react.default.createElement(Ansi, {
          onRender: this._onRender
        }, message);
      } else {
        return _react.default.createElement(Markdown, {
          tab: tab,
          extraClassName: "kui--markdown-from-repl",
          source: message.replace(/\\/g, '\\\\').replace(/\n/g, '\n\n'),
          onRender: this._onRender
        });
      }
    } else if ((0, _core.isCommentaryResponse)(response)) {
      return _react.default.createElement("span", {
        className: "flex-fill flex-layout flex-align-stretch"
      }, _react.default.createElement(Commentary, Object.assign({}, response.props, {
        repl: this.repl,
        tab: tab,
        execUUID: this.props.execUUID,
        onRender: this._onRender,
        willRemove: this.props.willRemove,
        willUpdateCommand: this.props.willUpdateCommand,
        willUpdateResponse: text => {
          response.props.children = text;
        }
      })));
    } else if ((0, _core.isRadioTable)(response)) {
      this.onRender();
      return _react.default.createElement(_2.KuiContext.Consumer, null, config => _react.default.createElement(RadioTableSpi, {
        table: response,
        title: !config.disableTableTitle,
        repl: this.repl
      }));
    } else if ((0, _core.isTable)(response)) {
      const renderBottomToolbar = true;
      const isLargeTable = response.body.length >= 50;
      const renderGrid = isLargeTable && (response.allowedPresentations === undefined || response.allowedPresentations.indexOf('grid') >= 0);
      return (0, _Table.default)(tab, this.repl, response, undefined, renderBottomToolbar, renderGrid, this._onRender, this.props.isWidthConstrained);
      // ^^^ Notes: typescript doesn't like this, and i don't know why:
      // "is not assignable to type IntrinsicAttributes..."
      // <PaginatedTable {...props} />
    } else if ((0, _core.isMixedResponse)(response)) {
      if (response.every(_ => typeof _ === 'string' || typeof _ === 'number' || typeof _ === 'boolean')) {
        return _react.default.createElement("pre", {
          className: "break-all"
        }, "[", response.toString(), "]");
      }
      return _react.default.createElement(_react.default.Fragment, null, response.map((part, idx) => _react.default.createElement(Scalar, Object.assign({}, this.props, {
        key: idx,
        response: part
      }))));
    } else if ((0, _core.isReactResponse)(response)) {
      this.onRender();
      return response.react;
    } else if (_core.Util.isHTML(response)) {
      // ^^^ intentionally using an "else" so that typescript double
      // checks that we've covered every case of ScalarResponse
      this.onRender();
      return _react.default.createElement(_HTMLDom.default, {
        content: response
      });
    } else if ((0, _core.isMarkdownResponse)(response)) {
      return _react.default.createElement(Markdown, {
        tab: tab,
        source: response.content,
        onRender: this._onRender
      });
    } else if ((0, _core.isRandomErrorResponse1)(response)) {
      // maybe this is an error response from some random API?
      return _react.default.createElement(Markdown, {
        tab: tab,
        source: strings(response.message ? 'randomError1WithMessage' : 'randomError1', response.code, response.message),
        onRender: this._onRender
      });
    } else if ((0, _core.isRandomErrorResponse2)(response)) {
      // maybe this is an error response from some random API?
      return _react.default.createElement(Markdown, {
        tab: tab,
        source: strings('randomError2', response.errno),
        onRender: this._onRender
      });
    } else if ((0, _core.isMultiModalResponse)(response)) {
      return _react.default.createElement(_MutabilityContext.MutabilityContext.Consumer, null, value => _react.default.createElement(TopNavSidecar, {
        uuid: tab.uuid,
        tab: tab,
        execUUID: this.props.execUUID,
        active: true,
        response: response,
        executable: value.executable,
        onRender: this.props.onRender,
        willChangeSize: this.props.willChangeSize,
        argvNoOptions: this.props.completeEvent ? this.props.completeEvent.argvNoOptions : undefined,
        parsedOptions: this.props.completeEvent ? this.props.completeEvent.parsedOptions : undefined
      }));
    } else if ((0, _core.isNavResponse)(response)) {
      return _react.default.createElement(LeftNavSidecar, {
        uuid: tab.uuid,
        tab: tab,
        execUUID: this.props.execUUID,
        active: true,
        response: response,
        onRender: this.props.onRender,
        willChangeSize: this.props.willChangeSize,
        argvNoOptions: this.props.completeEvent ? this.props.completeEvent.argvNoOptions : undefined,
        parsedOptions: this.props.completeEvent ? this.props.completeEvent.parsedOptions : undefined
      });
    } else if ((0, _core.isAbortableResponse)(response)) {
      this.onRender();
      return this.renderResponse(response.response);
    }
    console.error('unexpected response from Scalar:', this.props.response);
    this.onRender();
    return _react.default.createElement("pre", {
      className: "oops"
    }, "Internal Error in command execution");
  }
  render() {
    if (this.state.catastrophicError) {
      return _react.default.createElement("div", {
        className: "oops"
      }, this.state.catastrophicError.toString());
    }
    try {
      return this.renderResponse(this.props.response);
    } catch (err) {
      console.error('catastrophic error rendering Scalar', err);
      return _react.default.createElement("pre", null, err.toString());
    }
  }
}
exports.default = Scalar;