"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyboardLoop = void 0;
const readline = __importStar(require("node:readline"));
const process = __importStar(require("node:process"));
const node_core_library_1 = require("@rushstack/node-core-library");
const terminal_1 = require("@rushstack/terminal");
const executionUtilities_1 = require("../../utilities/executionUtilities");
// TODO: Integrate these into the AnsiEscape API in @rushstack/terminal
// As part of that work we should generalize the "Colorize" API to support more general
// terminal escapes, and simplify the interface for that API.
const ANSI_ESCAPE_SHOW_CURSOR = '\u001B[?25l';
const ANSI_ESCAPE_HIDE_CURSOR = '\u001B[?25h';
class KeyboardLoop {
    constructor() {
        this._cursorHidden = false;
        this._onKeypress = (character, key) => {
            if (key.name === 'c' && key.ctrl && !key.meta && !key.shift) {
                // Intercept CTRL+C
                process.kill(process.pid, 'SIGINT');
                return;
            }
            try {
                this.onKeypress(character, key);
            }
            catch (error) {
                throw new node_core_library_1.InternalError('Uncaught exception in Prompter.onKeypress(): ' + error.toString());
            }
        };
        this.stdin = process.stdin;
        this.stderr = process.stderr;
    }
    get capturedInput() {
        return this._readlineInterface !== undefined;
    }
    _captureInput() {
        if (this._readlineInterface) {
            return;
        }
        this._checkForTTY();
        this._readlineInterface = readline.createInterface({ input: this.stdin });
        readline.emitKeypressEvents(process.stdin);
        this.stdin.setRawMode(true);
        this.stdin.addListener('keypress', this._onKeypress);
    }
    _checkForTTY() {
        var _a;
        // Typescript thinks setRawMode always extists, but we're testing that assumption here.
        if (this.stdin.isTTY && this.stdin.setRawMode) {
            return;
        }
        if (executionUtilities_1.IS_WINDOWS) {
            const shell = (_a = process.env.SHELL) !== null && _a !== void 0 ? _a : '';
            if (shell.toUpperCase().endsWith('BASH.EXE')) {
                // Git Bash has a known problem where the Node.js TTY is lost when invoked via an NPM binary script.
                // eslint-disable-next-line no-console
                console.error(terminal_1.Colorize.red('ERROR: It appears that Rush was invoked from Git Bash shell, which does not support the\n' +
                    'TTY mode for interactive input that is required by this feature.') +
                    '\n\nKnown workarounds are:\n' +
                    '- Invoke Rush using "winpty rush.cmd" instead of "rush"\n' +
                    '- Or add this to your .bashrc:  alias rush="winpty rush.cmd"\n' +
                    '- Or create a Git Bash shortcut icon that launches\n' +
                    '  "C:\\Program Files\\Git\\bin\\bash.exe" instead of "git-bash.exe"\n\n' +
                    'For details, refer to https://github.com/microsoft/rushstack/issues/3217');
                throw new node_core_library_1.AlreadyReportedError();
            }
        }
        // eslint-disable-next-line no-console
        console.error(terminal_1.Colorize.red('ERROR: Rush was invoked by a command whose STDIN does not support the TTY mode for\n' +
            'interactive input that is required by this feature.') + '\n\nTry invoking "rush" directly from your shell.');
        throw new node_core_library_1.AlreadyReportedError();
    }
    _uncaptureInput() {
        if (!this._readlineInterface) {
            return;
        }
        this.stdin.removeListener('keypress', this._onKeypress);
        this.stdin.setRawMode(false);
        this._readlineInterface.close();
        this._readlineInterface = undefined;
    }
    hideCursor() {
        if (this._cursorHidden) {
            return;
        }
        this._cursorHidden = true;
        this.stderr.write(ANSI_ESCAPE_SHOW_CURSOR);
    }
    unhideCursor() {
        if (!this._cursorHidden) {
            return;
        }
        this._cursorHidden = false;
        this.stderr.write(ANSI_ESCAPE_HIDE_CURSOR);
    }
    async startAsync() {
        try {
            this._captureInput();
            this.onStart();
            await new Promise((resolve, reject) => {
                this._resolvePromise = resolve;
                this._rejectPromise = reject;
            });
        }
        finally {
            this._uncaptureInput();
            this.unhideCursor();
        }
    }
    resolveAsync() {
        if (!this._resolvePromise) {
            return;
        }
        this._resolvePromise();
        this._resolvePromise = undefined;
        this._rejectPromise = undefined;
    }
    rejectAsync(error) {
        if (!this._rejectPromise) {
            return;
        }
        this._rejectPromise(error);
        this._resolvePromise = undefined;
        this._rejectPromise = undefined;
    }
    /** @virtual */
    onStart() { }
    /** @virtual */
    onKeypress(character, key) { }
}
exports.KeyboardLoop = KeyboardLoop;
//# sourceMappingURL=KeyboardLoop.js.map