/*
 * 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 = (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 { ok } from 'assert';
import { v4 as uuid } from 'uuid';
import { Common, CLI, Keys, ReplExpect, Selectors, SidecarExpect } from '@kui-shell/test';
import { createNS, allocateNS, deleteNS, deletePodByName, waitForGreen, getTerminalText, waitForTerminalText, defaultModeForGet } from '@kui-shell/plugin-kubectl/tests/lib/k8s/utils';
const command = 'kubectl';
const podName = 'nginx';
const containerName = 'nginx';
// we will echo this text to this file
const ECHO_TEXT = `hello ${uuid()}`;
const ECHO_FILE_1 = '/tmp/kui-terminal-tab-test-1';
const ECHO_FILE_2 = '/tmp/kui-terminal-tab-test-2';
describe(`${command} Terminal tab ${process.env.MOCHA_RUN_TARGET || ''}`, function () {
    before(Common.before(this));
    after(Common.after(this));
    const ns = createNS();
    allocateNS(this, ns);
    const getPodAndOpenSidecar = () => {
        it(`should get pods via ${command} then click`, () => __awaiter(this, void 0, void 0, function* () {
            try {
                const selector = yield CLI.command(`${command} get pods ${podName} -n ${ns}`, this.app).then(ReplExpect.okWithCustom({ selector: Selectors.BY_NAME(podName) }));
                // wait for the badge to become green
                yield waitForGreen(this.app, selector);
                // now click on the table row
                yield this.app.client.click(`${selector} .clickable`);
                yield SidecarExpect.open(this.app)
                    .then(SidecarExpect.mode(defaultModeForGet))
                    .then(SidecarExpect.showing(podName));
            }
            catch (err) {
                return Common.oops(this, true)(err);
            }
        }));
    };
    const switchTo = (mode) => __awaiter(this, void 0, void 0, function* () {
        yield this.app.client.waitForVisible(Selectors.SIDECAR_MODE_BUTTON(mode));
        yield this.app.client.click(Selectors.SIDECAR_MODE_BUTTON(mode));
        yield this.app.client.waitForVisible(Selectors.SIDECAR_MODE_BUTTON_SELECTED(mode));
    });
    /** sleep for the given number of seconds */
    const sleep = (nSecs) => new Promise(resolve => setTimeout(resolve, nSecs * 1000));
    /** switch to terminal tab, echo into file, and confirm echoed text */
    const echoInTerminalTabAndConfirm = (ECHO_FILE) => {
        it('should show terminal tab', () => __awaiter(this, void 0, void 0, function* () {
            try {
                yield switchTo('terminal');
                yield SidecarExpect.toolbarText({
                    type: 'info',
                    text: `Connected to container ${containerName}`,
                    exact: false
                })(this.app);
                yield sleep(5);
                this.app.client.keys(`echo ${ECHO_TEXT} > ${ECHO_FILE}${Keys.ENTER}`);
            }
            catch (err) {
                return Common.oops(this, true)(err);
            }
        }));
        it(`should confirm echoed text via ${command} exec`, () => __awaiter(this, void 0, void 0, function* () {
            try {
                yield CLI.command(`${command} exec ${podName} -c ${containerName} -n ${ns} -- cat ${ECHO_FILE}`, this.app)
                    .then(ReplExpect.okWithString(ECHO_TEXT))
                    .catch(Common.oops(this, true));
            }
            catch (err) {
                yield Common.oops(this, true)(err);
            }
        }));
    };
    const doRetry = (toolbar) => {
        it('should click retry button', () => __awaiter(this, void 0, void 0, function* () {
            try {
                yield this.app.client.waitForVisible(Selectors.SIDECAR_MODE_BUTTON('retry-streaming'));
                yield this.app.client.click(Selectors.SIDECAR_MODE_BUTTON('retry-streaming'));
                yield SidecarExpect.toolbarText(toolbar)(this.app);
            }
            catch (err) {
                return Common.oops(this, true)(err);
            }
        }));
    };
    /** switch to terminal tab, exit with 1, see error in toolbar and click retry button */
    const exitTerminalTabAndRetry = () => {
        it('should show terminal tab and exit with error', () => __awaiter(this, void 0, void 0, function* () {
            try {
                yield this.app.client.waitForVisible(Selectors.SIDECAR_MODE_BUTTON('terminal'));
                yield this.app.client.click(Selectors.SIDECAR_MODE_BUTTON('terminal'));
                yield this.app.client.waitForVisible(Selectors.SIDECAR_MODE_BUTTON_SELECTED('terminal'));
                yield SidecarExpect.toolbarText({
                    type: 'info',
                    text: `Connected to container ${containerName}`,
                    exact: false
                })(this.app);
                yield new Promise(resolve => setTimeout(resolve, 5000));
                this.app.client.keys(`exit 1${Keys.ENTER}`);
                yield SidecarExpect.toolbarText({ type: 'error', text: 'has closed', exact: false })(this.app);
            }
            catch (err) {
                return Common.oops(this, true)(err);
            }
        }));
        doRetry({
            type: 'info',
            text: `Connected to container ${containerName}`,
            exact: false
        });
    };
    // needed to force the dom renderer for webpack/browser-based tests; see ExecIntoPod
    Common.setDebugMode.bind(this)();
    it(`should create sample pod from URL via ${command}`, () => {
        return CLI.command(`${command} create -f https://raw.githubusercontent.com/kubernetes/examples/master/staging/pod -n ${ns}`, this.app)
            .then(ReplExpect.okWithCustom({ selector: Selectors.BY_NAME('nginx') }))
            .then((selector) => waitForGreen(this.app, selector))
            .catch(Common.oops(this, true));
    });
    getPodAndOpenSidecar();
    echoInTerminalTabAndConfirm(ECHO_FILE_1);
    getPodAndOpenSidecar();
    exitTerminalTabAndRetry();
    echoInTerminalTabAndConfirm(ECHO_FILE_2);
    const getText = getTerminalText.bind(this);
    const waitForText = waitForTerminalText.bind(this);
    it('should re-focus and xoff the terminal when we switch to a different sidecar tab', () => __awaiter(this, void 0, void 0, function* () {
        try {
            console.error('1');
            yield switchTo('raw');
            yield sleep(3);
            console.error('2');
            yield switchTo('terminal');
            yield sleep(3);
            console.error('3');
            const elts = yield this.app.client.elements(`${Selectors.SIDECAR_TAB_CONTENT} .xterm-rows`);
            console.error('3b', elts && elts.value.length);
            yield this.app.client.keys(`while true; do echo hi; sleep 1; done${Keys.ENTER}`);
            console.error('4');
            yield waitForText('hi');
            const textBeforeSwitch = yield getText();
            const nLinesBefore = textBeforeSwitch.split(/\n/).length;
            console.error('5', nLinesBefore);
            yield switchTo('raw');
            yield sleep(10);
            yield switchTo('terminal');
            const textAfterSwitch = yield getText();
            const nLinesAfter = textAfterSwitch.split(/\n/).length;
            console.error('6', nLinesAfter);
            // we slept for 10 seconds, and our while loop emits "hi" every
            // second. we shouldn't have anywhere near 10 new newlines now:
            ok(nLinesAfter - nLinesBefore < 5);
        }
        catch (err) {
            yield Common.oops(this, true)(err);
        }
    }));
    it('should properly exit the terminal', () => __awaiter(this, void 0, void 0, function* () {
        try {
            yield this.app.client.keys(Keys.ctrlC);
            yield this.app.client.keys(`exit${Keys.ENTER}`);
            yield SidecarExpect.toolbarText({ type: 'error', text: 'has closed', exact: false })(this.app);
        }
        catch (err) {
            yield Common.oops(this, true)(err);
        }
    }));
    deletePodByName(this, podName, ns);
    doRetry({ type: 'error', text: 'has closed', exact: false });
    deleteNS(this, ns);
});
//# sourceMappingURL=terminal-tab.js.map