"use strict";

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

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

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

var _carbonComponentsReact = require("carbon-components-react");

var _Icons = _interopRequireDefault(require("../../spi/Icons"));

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-core-support');
const strings2 = (0, _core.i18n)('plugin-client-common');

class Tab extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      title: strings('Tab'),
      processing: false,
      isFreshlyCreated: true,
      topTabNames: props.topTabNames || 'command'
    };

    if (!props.topTabNames) {
      setTimeout(() => __awaiter(this, void 0, void 0, function* () {
        const {
          theme
        } = yield (0, _core.findThemeByName)((yield (0, _core.getPersistedThemeChoice)()) || (yield (0, _core.getDefaultTheme)()));

        if (theme.topTabNames) {
          this.setState({
            topTabNames: theme.topTabNames
          });
        }
      }));
    }

    this.addCommandEvaluationListeners();
  }

  componentWillUnmount() {
    this.removeCommandEvaluationListeners();
  }

  removeCommandEvaluationListeners() {
    _core.eventBus.offCommandStart(this.props.uuid, this.onCommandStart);

    _core.eventBus.offCommandComplete(this.props.uuid, this.onCommandStart);

    _core.eventChannelUnsafe.off('/theme/change', this.onThemeChange);
  }
  /**
   * Register any command evaluation listeners, i.e. when the REPL finishes evaluating a command.
   *
   */


  addCommandEvaluationListeners() {
    this.onCommandComplete = event => {
      if (this.props.uuid === event.tab.state.uuid) {
        if (event.execType !== undefined && event.execType !== _core.ExecType.Nested && event.route) {
          // ignore nested, which means one plugin calling another
          this.setState({
            processing: false
          });
        }

        this.setState({
          processing: false
        });
      }
    };

    this.onCommandStart = event => {
      if (this.props.uuid === event.tab.state.uuid) {
        if (event.execType !== undefined && event.execType !== _core.ExecType.Nested && event.route) {
          // ignore nested, which means one plugin calling another
          // debug('got event', event)
          if (event.route !== undefined && !event.route.match(/^\/(tab|getting\/started)/) // ignore our own events and help
          ) {
              if (this.isUsingCommandName()) {
                this.setState({
                  processing: true,
                  title: event.command || this.state.title,
                  isFreshlyCreated: false
                });
                return;
              }
            }

          this.setState({
            processing: true,
            isFreshlyCreated: false
          });
        }
      }
    };

    this.onThemeChange = ({
      themeModel
    }) => {
      this.setState({
        topTabNames: themeModel.topTabNames || 'command'
      });
    };

    _core.eventBus.onCommandStart(this.props.uuid, this.onCommandStart);

    _core.eventBus.onCommandComplete(this.props.uuid, this.onCommandComplete);

    _core.eventChannelUnsafe.on('/theme/change', this.onThemeChange);
  }

  isUsingCommandName() {
    return this.state.topTabNames === 'command'; // && !document.body.classList.contains('kui--alternate')
  }

  render() {
    return React.createElement(_carbonComponentsReact.HeaderMenuItem, {
      href: "#",
      "data-tab-names": this.state.topTabNames,
      "data-fresh": this.state.isFreshlyCreated,
      className: 'kui--tab kui--tab-navigatable' + (this.props.active ? ' kui--tab--active' : '') + (this.state.processing ? ' processing' : ''),
      "data-tab-button-index": this.props.idx + 1,
      "aria-label": "tab",
      onMouseDown: evt => {
        evt.preventDefault();
        evt.stopPropagation();
      },
      onClick: () => {
        this.props.onSwitchTab(this.props.idx);
      }
    }, React.createElement("div", {
      className: "kui--tab--label"
    }, this.isUsingCommandName() && this.state.title, !this.isUsingCommandName() && React.createElement("span", {
      className: "kui--tab--label-text"
    }, strings('Tab'), " "), !this.isUsingCommandName() && React.createElement("span", {
      className: "kui--tab--label-index"
    })), this.props.closeable && React.createElement("div", {
      className: "kui--tab-close",
      title: strings2('Close this tab'),
      onClick: evt => {
        evt.stopPropagation();
        evt.preventDefault();
        this.props.onCloseTab(this.props.idx);
      }
    }, React.createElement(_Icons.default, {
      icon: "WindowClose",
      focusable: "false",
      preserveAspectRatio: "xMidYMid meet",
      "aria-hidden": "true"
    })));
  }

}

exports.default = Tab;