"use strict";

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

var _debug = _interopRequireDefault(require("debug"));

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

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

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

var _context = _interopRequireDefault(require("./context"));

var _2 = require("../..");

var _WelcomeLight = _interopRequireDefault(require("../../../icons/png/WelcomeLight.png"));

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; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * 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());
  });
}; // FIXME:

/* eslint-disable react/prop-types */


const debug = (0, _debug.default)('<Kui/>');
const strings = (0, _core.i18n)('client');
const Popup = React.lazy(() => Promise.resolve().then(() => require('./Popup')));
const defaultThemeProperties = {
  components: 'carbon',
  topTabNames: 'fixed'
};
/**
 * Render the main body of our client.
 *
 * |Notes on Session Initialization|: to provide custom views for
 * session initialization (only relevant for browser-based hosted
 * Kui), you can instantiate <Kui/> with these properties (defined in
 * KuiConfiguration), show here with some sample views:
 *
 * <Kui
 *    loading={<div className="kui--hero-text">Hold on...</div>}
 *    reinit={<div className="kui--hero-text">Connection broken...</div>}
 *    loadingError={err => <div className="kui--hero-text">{err.toString()}</div>}
 *    loadingDone={<div>Welcome to Kui</div>}
 * />
 *
 */

class Kui extends React.PureComponent {
  constructor(props) {
    super(props);

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

    setTimeout(() => __awaiter(this, void 0, void 0, function* () {
      const {
        theme
      } = yield (0, _core.findThemeByName)((yield (0, _core.getPersistedThemeChoice)()) || (yield (0, _core.getDefaultTheme)()));
      this.setState(curState => {
        const stateWithThemeProps = Object.assign({}, theme, curState);
        debug('state with theme props', stateWithThemeProps);
        return stateWithThemeProps;
      });
    }));

    if (!props.noBootstrap) {
      Promise.resolve().then(() => require('@kui-shell/core')).then(_ => _.bootIntoSandbox()).then(() => {
        this.setState({
          isBootstrapped: true
        });
      });
    }

    try {
      this.state = Object.assign({}, this.defaultSessionBehavior(), this.defaultFeatureFlag(), props, {
        isBootstrapped: !!props.noBootstrap
      });
      debug('initial state:inBrowser?', (0, _core.inBrowser)());
      debug('initial state:given properties', props);
      debug('initial state:final value', this.state);
    } catch (err) {
      console.log('using default configuration');
      this.state = {
        isBootstrapped: !!props.noBootstrap
      };
    }
  }

  defaultFeatureFlag() {
    return {
      sidecarName: 'breadcrumb',
      showWelcomeMax: -1
    };
  }

  defaultLoading() {
    return React.createElement(_2.Loading, {
      className: "somewhat-larger-text",
      description: strings('Please wait while we connect to your cluster')
    });
  }

  defaultReinit() {
    return React.createElement(_2.Alert, {
      hideCloseButton: true,
      alert: {
        type: 'error',
        title: strings('Lost connection to your cluster'),
        body: strings('Attempting to reconnect...')
      }
    });
  }

  defaultLoadingDone() {
    return repl => !(0, _core.inBrowser)() ? undefined : React.createElement(_Card.default, {
      titleInHeader: true,
      bodyInHeader: true,
      title: strings('Successfully connected to your cluster'),
      repl: repl,
      icon: _WelcomeLight.default
    }, strings('loadingDone:content'));
  }

  defaultLoadingError() {
    return err => React.createElement(_2.Alert, {
      alert: {
        type: 'error',
        title: strings('Error connecting to your cluster'),
        body: err.toString()
      }
    });
  }
  /**
   * For browser-based clients, this defines the default UI for
   * session initialization.
   *
   */


  defaultSessionBehavior() {
    const behavior = !(0, _core.inBrowser)() ? {} : {
      loading: this.defaultLoading(),
      reinit: this.defaultReinit(),
      loadingError: this.defaultLoadingError(),
      loadingDone: this.defaultLoadingDone()
    };
    debug('defaultSessionBehavior', behavior);
    return behavior;
  }

  onThemeChange({
    themeModel
  }) {
    this.setState(curState => {
      // note the priority order, from highest to lowest:
      //  1) any properties defined by the theme (since we just switched themes)
      //  2) any properties defined by the container of this <Kui/>
      //  3) default choices
      //  4) any prior state
      // re: ordering of 3 and 4, see https://github.com/IBM/kui/issues/4423
      const stateAfterThemeChange = Object.assign({}, curState, defaultThemeProperties, this.props, themeModel);
      debug('state after theme change', stateAfterThemeChange);
      return stateAfterThemeChange;
    });
  }

  componentDidCatch(error, errorInfo) {
    console.error(error, errorInfo);
  }

  render() {
    if (!this.state.isBootstrapped) {
      return React.createElement(_2.Loading, null);
    }

    if (this.props.isPopup && this.props.commandLine) {
      return React.createElement(_context.default.Provider, {
        value: this.state
      }, React.createElement(React.Suspense, {
        fallback: React.createElement("div", null)
      }, React.createElement(Popup, {
        commandLine: this.props.commandLine
      }, this.props.children)));
    } else {
      const bottom = !!this.props.bottomInput && React.createElement(_2.InputStripe, null, this.props.bottomInput);
      return React.createElement(_context.default.Provider, {
        value: this.state
      }, React.createElement("div", {
        className: "kui--full-height"
      }, React.createElement(_2.TabContainer, {
        noActiveInput: !!this.props.bottomInput,
        bottom: bottom
      }, React.createElement(_2.ComboSidecar, null)), this.props.toplevel, React.createElement(_2.StatusStripe, null, this.props.children)));
    }
  }

}

exports.Kui = Kui;
var _default = Kui;
exports.default = _default;