"use strict";

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

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

var _uuid = require("uuid");

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

var _Card = _interopRequireDefault(require("../spi/Card"));

var _same = _interopRequireDefault(require("./util/same"));

var _BaseSidecar = require("./Sidecar/BaseSidecar");

var _LivePaginatedTable = _interopRequireDefault(require("../Content/Table/LivePaginatedTable"));

var _PaginatedTable = require("../Content/Table/PaginatedTable");

var _CircularBuffer = _interopRequireDefault(require("./util/CircularBuffer"));

var _Breadcrumb = _interopRequireDefault(require("../spi/Breadcrumb"));

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

class WatchPane extends React.PureComponent {
  constructor(props) {
    super(props);
    const onResponse = this.onResponse.bind(this);

    _core.eventBus.onScalarResponse(this.props.uuid, onResponse);

    this.state = {
      current: undefined,
      history: undefined
    };
  }

  onResponse(tab, response, _, argvNoOptions, parsedOptions, __, evaluatorOptions, execOptions, command) {
    if ((0, _core.isTable)(response) && (0, _core.isWatchable)(response) && evaluatorOptions.alwaysViewIn !== 'Terminal' && execOptions.alwaysViewIn !== 'Terminal') {
      this.setState(curState => {
        const cwd = (0, _BaseSidecar.cwd)();
        const existingIdx = curState.history ? curState.history.findIndex((0, _same.default)(argvNoOptions, parsedOptions, cwd)) : -1;
        const current = {
          key: (0, _uuid.v4)(),
          response,
          argvNoOptions,
          parsedOptions,
          command,
          cwd
        };

        if (current) {
          this.props.openWatchPane();

          if (!curState.history) {
            return {
              current,
              history: new _CircularBuffer.default(current, this.capacity())
            };
          } else {
            if (existingIdx === -1) {
              curState.history.push(current);
            } else {
              curState.history.update(existingIdx, current);
            }

            return {
              current,
              history: curState.history
            };
          }
        }
      });
    }
  }
  /** Keep this in sync with WatchPane.scss $num-columns */


  capacity() {
    return 4;
  }
  /** re-execute the command, but display the watch result in terminal */


  watchInTerminal(command) {
    this.props.tab.REPL.pexec(command, {
      alwaysViewIn: 'Terminal'
    });
  }
  /** `Card Actions`, will be rendred as `Dropdown` */


  actions(history, watcherIdx) {
    const watchInTerminal = {
      label: strings('Show as table'),
      handler: this.watchInTerminal.bind(this, history.command)
    };
    const stopWatching = {
      label: strings('Stop watching'),
      handler: this.clearSubPane.bind(this, history.response, watcherIdx)
    };
    return [watchInTerminal, stopWatching];
  }
  /** render subpane header as Breadcrumb */


  header(response, idx) {
    const prefixBreadcrumbs = [{
      label: `Watcher ${idx + 1}`
    }];
    const breadcrumbs = (0, _PaginatedTable.getBreadcrumbsFromTable)(response, prefixBreadcrumbs);
    return React.createElement(_Breadcrumb.default, {
      repl: this.props.tab.REPL,
      breadcrumbs: breadcrumbs.length > 0 && breadcrumbs
    });
  }
  /** abort the watchable job and clear the watch pane */


  clearSubPane(response, idx) {
    // abort the watchable job
    response.watch.abort(); // remove the history entry from circular buffer

    this.state.history.popAt(idx); // force re-rendering

    this.forceUpdate(); // remove the watch pane if there's no watcher

    if (!this.state.history || this.state.history.length === 0) {
      this.props.closeWatchPane();
    }
  }

  render() {
    return React.createElement("div", {
      className: "kui--watch-pane"
    }, this.state.history && this.state.history.length !== 0 && Array(this.capacity()).fill(undefined).map((_, idx) => {
      const history = this.state.history.peekAt(idx);
      return React.createElement(_Card.default, {
        className: `kui--card kui--screenshotable kui--card-${idx + 1}`,
        actions: history && this.actions(history, idx),
        header: history && this.header(history.response, idx),
        key: history ? history.key : idx
      }, history && React.createElement("div", {
        className: "kui--sub-card"
      }, React.createElement(_LivePaginatedTable.default, {
        tab: this.props.tab,
        repl: this.props.tab.REPL,
        response: history.response,
        asGrid: true,
        title: false,
        toolbars: false,
        paginate: false,
        onRender: () => false
      })));
    }));
  }

}

exports.default = WatchPane;