/*
 * 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 = (this && this.__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());
    });
};
import Debug from 'debug';
import { inBrowser, inElectron, i18n } from '@kui-shell/core';
import { InProcessChannel } from './channel';
import { setOnline, setOffline } from './ui';
const strings = i18n('plugin-bash-like');
const debug = Debug('plugins/bash-like/pty/session');
/**
 * Return the cached websocket for the given tab
 *
 */
export function getChannelForTab(tab) {
    return tab['ws'];
}
/**
 * Return the session for the given tab
 *
 */
export function getSessionForTab(tab) {
    return __awaiter(this, void 0, void 0, function* () {
        if (tab['_kui_session'] === undefined && inElectron()) {
            const channel = new 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
 *
 */
export function pollUntilOnline(tab) {
    return new Promise(resolve => {
        let isOnline = false;
        const initialSetOffline = setTimeout(() => {
            if (!isOnline) {
                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);
                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
 *
 */
export function init(registrar) {
    return __awaiter(this, void 0, void 0, function* () {
        const { proxyServer } = yield import('@kui-shell/client/config.d/proxy.json').catch(() => {
            console.log('using default proxy configuration');
            return { proxyServer: { enabled: false } };
        });
        if (inBrowser() && proxyServer.enabled !== false) {
            debug('initializing pty sessions');
            const { eventBus } = yield import('@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);
                }
            }));
        }
    });
}
//# sourceMappingURL=session.js.map