"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getChannelForTab = getChannelForTab;
exports.getSessionForTab = getSessionForTab;
exports.pollUntilOnline = pollUntilOnline;
exports.init = init;

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

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

var _channel = require("./channel");

var _ui = require("./ui");

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

/*
 * Copyright 2019 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-bash-like');
const debug = (0, _debug.default)('plugins/bash-like/pty/session');
/**
 * Return the cached websocket for the given tab
 *
 */

function getChannelForTab(tab) {
  return tab['ws'];
}
/**
 * Return the session for the given tab
 *
 */


function getSessionForTab(tab) {
  return __awaiter(this, void 0, void 0, function* () {
    if (tab['_kui_session'] === undefined && (0, _core.inElectron)()) {
      const channel = new _channel.InProcessChannel();
      yield channel.init();
      tab['_kui_session'] = Promise.resolve(channel);
      return tab['_kui_session'];
    } else {
      return tab['_kui_session'];
    }
  });
}
/**
 * Keep trying until we can establish a session
 *
 */


function pollUntilOnline(tab) {
  return new Promise(resolve => {
    let isOnline = false;
    const initialSetOffline = setTimeout(() => {
      if (!isOnline) {
        (0, _ui.setOffline)();
      }
    }, 5000);

    const once = (iter = 0) => {
      debug('trying to establish session', tab);
      return tab.REPL.qexec('echo initializing session', undefined, undefined, {
        tab
      }).then(() => {
        isOnline = true;
        clearTimeout(initialSetOffline);
        (0, _ui.setOnline)();
        resolve();
      }).catch(error => {
        const err = error;

        if (err.code !== 503) {
          // don't bother complaining too much about connection refused
          console.error('error establishing session', err.code, err.statusCode, err);
        }

        setTimeout(() => once(iter + 1), iter < 10 ? 2000 : iter < 100 ? 4000 : 10000);
        return strings('Could not establish a new session');
      });
    };

    once();
  });
}
/**
 * This function establishes a promise of a websocket channel for the
 * given tab
 *
 */


function newSessionForTab(tab) {
  return __awaiter(this, void 0, void 0, function* () {
    // eslint-disable-next-line no-async-promise-executor
    tab['_kui_session'] = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
      try {
        yield pollUntilOnline(tab);
        tab.classList.add('kui--session-init-done');
        resolve(getChannelForTab(tab));
      } catch (err) {
        reject(err);
      }
    }));
    yield tab['_kui_session'];
  });
}
/**
 * Initialize per-tab websocket session management
 *
 */


function init(registrar) {
  return __awaiter(this, void 0, void 0, function* () {
    const {
      proxyServer
    } = yield Promise.resolve().then(() => require('@kui-shell/client/config.d/proxy.json')).catch(() => {
      console.log('using default proxy configuration');
      return {
        proxyServer: {
          enabled: false
        }
      };
    });

    if ((0, _core.inBrowser)() && proxyServer.enabled !== false) {
      debug('initializing pty sessions');
      const {
        eventBus
      } = yield Promise.resolve().then(() => require('@kui-shell/core'));
      registrar.registerSessionInitializer(newSessionForTab); // listen for closed tabs

      eventBus.on('/tab/close', tab => __awaiter(this, void 0, void 0, function* () {
        try {
          debug('closing session for tab');
          getChannelForTab(tab).close();
        } catch (err) {
          console.error('error terminating session for closed tab', err);
        }
      }));
    }
  });
}