"use strict";

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

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

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

var _BlockModel = require("./BlockModel");

var _Scalar = _interopRequireDefault(require("../../../Content/Scalar/"));

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

class Output extends React.PureComponent {
  constructor(props) {
    super(props);
    const streamingConsumer = this.streamingConsumer.bind(this);
    const tabUUID = props.uuid;

    if ((0, _BlockModel.isProcessing)(props.model)) {
      _core.eventChannelUnsafe.on(`/command/stdout/${tabUUID}/${props.model.execUUID}`, streamingConsumer);
    }

    this.state = {
      isResultRendered: false,
      streamingOutput: [],
      streamingConsumer
    };
  } // eslint-disable-next-line @typescript-eslint/no-unused-vars


  streamingConsumer(part) {
    return __awaiter(this, void 0, void 0, function* () {
      if ((0, _BlockModel.hasUUID)(this.props.model)) {
        this.setState(curState => ({
          streamingOutput: curState.streamingOutput.concat([part])
        }));
        this.props.onRender();

        _core.eventChannelUnsafe.emit(`/command/stdout/done/${this.props.uuid}/${this.props.model.execUUID}`);
      }
    });
  }

  static getDerivedStateFromProps(props, state) {
    if ((0, _BlockModel.isFinished)(props.model) && !state.isResultRendered) {
      const tabUUID = props.uuid;

      if (!(0, _BlockModel.isEmpty)(props.model)) {
        _core.eventChannelUnsafe.off(`/command/stdout/${tabUUID}/${props.model.execUUID}`, state.streamingConsumer);
      }

      if (!(0, _BlockModel.isEmpty)(props.model) && !(0, _BlockModel.isCancelled)(props.model)) {
        props.onRender();
      }

      return {
        isResultRendered: true,
        streamingConsumer: undefined
      };
    } else {
      return state;
    }
  }

  onRender(assertHasContent) {
    if (this.props.onRender) {
      this.props.onRender();
    }

    this.setState({
      assertHasContent
    });
  }

  stream() {
    if (this.state.streamingOutput.length > 0) {
      return React.createElement("div", {
        className: "repl-result-like result-vertical",
        "data-stream": true
      }, this.state.streamingOutput.map((part, idx) => React.createElement(_Scalar.default, {
        key: idx,
        tab: this.props.tab,
        response: part,
        isPinned: this.props.isPinned,
        onRender: this.onRender.bind(this)
      })));
    }
  }

  result() {
    if ((0, _BlockModel.isProcessing)(this.props.model)) {
      return React.createElement("div", {
        className: "repl-result"
      });
    } else if ((0, _BlockModel.isEmpty)(this.props.model)) {
      // no result to display for these cases
      return React.createElement(React.Fragment, null);
    } else {
      const statusCode = (0, _BlockModel.isOops)(this.props.model) ? (0, _core.isCodedError)(this.props.model.response) ? this.props.model.response.code || this.props.model.response.statusCode : 500 : (0, _BlockModel.isFinished)(this.props.model) ? 0 : undefined;
      return React.createElement("div", {
        className: 'repl-result' + ((0, _BlockModel.isOops)(this.props.model) ? ' oops' : ''),
        "data-status-code": statusCode
      }, (0, _BlockModel.isCancelled)(this.props.model) ? React.createElement(React.Fragment, null) : React.createElement(_Scalar.default, {
        tab: this.props.tab,
        response: this.props.model.response,
        isPinned: this.props.isPinned,
        onRender: this.onRender.bind(this)
      }));
    }
  }

  cursor() {
    if ((0, _BlockModel.isProcessing)(this.props.model)) {
      return React.createElement("div", {
        className: "repl-result-spinner"
      }, React.createElement("div", {
        className: "repl-result-spinner-inner"
      }));
    }
  }

  isShowingSomethingInTerminal(block) {
    if ((0, _BlockModel.isFinished)(block) && !(0, _BlockModel.isCancelled)(block) && !(0, _BlockModel.isEmpty)(block)) {
      const {
        response
      } = block;
      return (0, _core.isReactResponse)(response) || (0, _core.isHTML)(response) || (0, _core.isMarkdownResponse)(response) || typeof response === 'string' && response.length > 0 || (0, _core.isTable)(response) && response.body.length > 0 || this.state.streamingOutput.length > 0;
    } else {
      return false;
    }
  }

  ok(hasContent) {
    if ((0, _BlockModel.isOk)(this.props.model)) {
      if (hasContent) {
        return React.createElement("div", {
          className: "ok"
        });
      } else if ((0, _core.isWatchable)(this.props.model.response)) {
        return this.props.isPinned ? React.createElement("div", {
          className: "kui--hero-text"
        }, strings('No resources')) : React.createElement("div", {
          className: "ok"
        }, strings('No resources'));
      } else {
        return React.createElement("div", {
          className: "ok"
        }, strings('ok'));
      }
    }
  }

  render() {
    const hasContent = this.state.assertHasContent !== undefined ? this.state.assertHasContent : this.isShowingSomethingInTerminal(this.props.model);
    return React.createElement("div", {
      className: 'repl-output result-vertical' + (hasContent ? ' repl-result-has-content' : '')
    }, this.stream(), this.result(), this.cursor(), this.ok(hasContent));
  }

}

exports.default = Output;