"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Command = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const util_1 = require("util");
const yargs_parser_1 = tslib_1.__importDefault(require("yargs-parser"));
const yargs_unparser_1 = tslib_1.__importDefault(require("yargs-unparser"));
const pjson = require('../package.json');
const deps_1 = tslib_1.__importDefault(require("./deps"));
const deprecatedCLI = (0, util_1.deprecate)(() => {
    return require('cli-ux').cli;
}, 'this.out and this.cli is deprecated. Please import "CliUx" from the @oclif/core module directly instead.');
class Command extends core_1.Command {
    constructor() {
        super(...arguments);
        this.base = `${pjson.name}@${pjson.version}`;
        this.allowArbitraryFlags = false;
    }
    get heroku() {
        var _a, _b;
        if (this._heroku)
            return this._heroku;
        const options = {
            debug: process.env.HEROKU_DEBUG === '1' || ((_a = process.env.HEROKU_DEBUG) === null || _a === void 0 ? void 0 : _a.toUpperCase()) === 'TRUE',
            debugHeaders: process.env.HEROKU_DEBUG_HEADERS === '1' || ((_b = process.env.HEROKU_DEBUG_HEADERS) === null || _b === void 0 ? void 0 : _b.toUpperCase()) === 'TRUE',
        };
        this._heroku = new deps_1.default.APIClient(this.config, options);
        return this._heroku;
    }
    get legacyHerokuClient() {
        if (this._legacyHerokuClient)
            return this._legacyHerokuClient;
        const HerokuClient = require('heroku-client');
        const options = {
            debug: this.config.debug,
            host: `${this.heroku.defaults.protocol || 'https:'}//${this.heroku.defaults.host ||
                'api.heroku.com'}`,
            token: this.heroku.auth,
            userAgent: this.heroku.defaults.headers['user-agent'],
        };
        this._legacyHerokuClient = new HerokuClient(options);
        return this._legacyHerokuClient;
    }
    get cli() {
        return deprecatedCLI();
    }
    get out() {
        return deprecatedCLI();
    }
    async parse(options, argv) {
        if (this.allowArbitraryFlags) {
            try {
                return await super.parse(options, argv);
            }
            catch (error) {
                const { flags: nonExistentFlags } = error;
                const parsed = (0, yargs_parser_1.default)(this.argv);
                const nonExistentFlagsWithValues = Object.assign({}, parsed);
                if (nonExistentFlags && nonExistentFlags.length > 0) {
                    this.warn(`You’re using a deprecated syntax with the [${nonExistentFlags}] flag.\nAdd a '--' (end of options) separator before the flags you’re passing through.`);
                    for (const flag of nonExistentFlags) {
                        const key = flag.replace('--', '');
                        delete parsed[key];
                    }
                }
                for (const key in parsed) {
                    if (Reflect.has(parsed, key)) {
                        delete nonExistentFlagsWithValues[key];
                    }
                }
                this.argv = (0, yargs_unparser_1.default)(parsed);
                const result = await super.parse(options, argv);
                result.nonExistentFlags = (0, yargs_unparser_1.default)(nonExistentFlagsWithValues);
                for (let index = 0; index < result.nonExistentFlags.length; index++) {
                    const positionalValue = result.nonExistentFlags[index];
                    const doubleHyphenRegex = /^--/;
                    const positionalValueIsFlag = doubleHyphenRegex.test(positionalValue);
                    if (positionalValueIsFlag) {
                        const nextElement = result.nonExistentFlags[index + 1] ? result.nonExistentFlags[index + 1] : '';
                        const nextElementIsFlag = doubleHyphenRegex.test(nextElement);
                        // eslint-disable-next-line max-depth
                        if (nextElement && !nextElementIsFlag) {
                            result.argv.push(`${positionalValue}=${nextElement}`);
                        }
                        else if (!nextElement || nextElementIsFlag) {
                            result.argv.push(`${positionalValue}=${true}`);
                        }
                    }
                }
                return result;
            }
        }
        return super.parse(options, argv);
    }
}
exports.Command = Command;
