"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _core = require("@kui-shell/core");
var _Scalar = _interopRequireDefault(require("../../../Content/Scalar"));
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 Ansi = _react.default.lazy(() => Promise.resolve().then(() => require('../../../Content/Scalar/Ansi')));
class StreamingConsumer extends _react.default.PureComponent {
  constructor() {
    super(...arguments);
    this.nope = () => {}; // eslint-disable-line @typescript-eslint/no-empty-function
    this._streamingOutput = [];
    this._streamingConsumer = this.streamingConsumer.bind(this);
  }
  static initStreamingState(execUUID) {
    return {
      execUUID,
      nStreamingOutputs: 0
    };
  }
  hasStreamingOutput() {
    return this.state.nStreamingOutputs > 0;
  }
  /** Accept one part of streaming output */
  streamingConsumer(part) {
    return __awaiter(this, void 0, void 0, function* () {
      const {
        tab
      } = this.props;
      const {
        execUUID
      } = this.state;
      // done with this part... not done with all parts
      const done = () => {
        // this.props.onRender()
        _core.Events.eventChannelUnsafe.emit(`/command/stdout/done/${tab.uuid}/${execUUID}`);
      };
      // part === null: the controller wants to clear prior output
      if (part === null) {
        // remove last output
        this._streamingOutput.pop();
        this.setState(curState => ({
          nStreamingOutputs: curState.nStreamingOutputs - 1
        }));
        done();
      } else {
        this._streamingOutput.push(Buffer.isBuffer(part) ? part.toString() : part);
        // use setTimeout to introduce hysteresis, so we aren't
        // forcing a react re-render for a bunch of tiny streaming
        // updates
        setTimeout(() => {
          this.setState({
            nStreamingOutputs: this._streamingOutput.length
          });
          setTimeout(done, 10);
        }, 10);
      }
    });
  }
  /** Render the streaming output */
  streamingOutput() {
    if (this.hasStreamingOutput()) {
      if (this._streamingOutput.every(_ => typeof _ === 'string')) {
        const combined = this._streamingOutput.join('');
        return _react.default.createElement(_react.default.Suspense, {
          fallback: _react.default.createElement("div", null)
        }, _react.default.createElement(Ansi, null, combined));
      }
      // onRender={this._onRender}
      //                willChangeSize={this.props.willChangeSize}
      //              willUpdateCommand={this._willUpdateCommand}
      //            isWidthConstrained={this.props.isWidthConstrained}
      return this._streamingOutput.map((part, idx) => _react.default.createElement(_react.default.Suspense, {
        fallback: _react.default.createElement("div", null),
        key: idx
      }, _react.default.createElement(_Scalar.default, {
        response: part,
        tab: this.props.tab,
        willChangeSize: this.nope,
        execUUID: this.state.execUUID
      })));
    }
  }
  clearPriorStreamingOutput() {
    this._streamingOutput = [];
    this.setState({
      nStreamingOutputs: 0
    });
  }
  /** Wrap the execution of the given `cmdline` with handling of streaming output */
  execWithStream(cmdline) {
    return __awaiter(this, void 0, void 0, function* () {
      this.clearPriorStreamingOutput();
      const streamingChannel = `/command/stdout/${this.props.tab.uuid}/${this.state.execUUID}`;
      try {
        _core.Events.eventChannelUnsafe.on(streamingChannel, this._streamingConsumer);
        return yield (0, _core.pexecInCurrentTab)(cmdline, this.props.tab, false, true, this.state.execUUID);
      } finally {
        _core.Events.eventChannelUnsafe.off(streamingChannel, this._streamingConsumer);
      }
    });
  }
}
exports.default = StreamingConsumer;