"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HelmResourceConfigurator = void 0;
const tslib_1 = require("tslib");
const inversify_1 = require("inversify");
const codiac_common_1 = require("@codiac.io/codiac-common");
const codiac_domain_1 = require("@codiac.io/codiac-domain");
const codiac_ops_common_1 = require("@codiac.io/codiac-ops-common");
const contracts_1 = require("../../apis/codiac-relay/contracts");
const ops_1 = require("../../ops");
const codiac_relay_1 = require("../../apis/codiac-relay");
const contracts_2 = require("@codiac.io/codiac-common/contracts");
/** Walks the user through the selection of an existing
 * or the declaration of a new image registry.
 */
let HelmResourceConfigurator = class HelmResourceConfigurator {
    constructor(codiacUser, relayClient, _ui, _styler, logger) {
        this.codiacUser = codiacUser;
        this.relayClient = relayClient;
        this._ui = _ui;
        this._styler = _styler;
        this.logger = logger;
        this.cloudProvider = codiac_domain_1.CloudProviderEnum.artifactHub;
    }
    captureImageRegistry() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                let output;
                try {
                    let code = contracts_1.ImageRegistryTypes.helm.concat("|", codiac_domain_1.CloudProviderEnum.artifactHub); // TEMPORARY: bc artifactHub is indeed a registry in the strictest sense, but not a repository.
                    let output = new codiac_domain_1.ImageRegistry(code, "to.be.determined.upon.selecting.package", this.cloudProvider, contracts_1.ImageRegistryTypes.helm);
                    output.useRemoteFiltering = true; // registry is huge, gotta let them perform the search remotely, not us locally.
                    resolve(output);
                }
                catch (err) {
                    // this.logger.error(`${err.name ?? ''} ${err.message ?? ''}`, err.stack);
                    reject(err);
                }
            }));
        });
    }
    /* ***********************************************************************************
    *   _                 _
    *  | |               (_)
    *  | |     ___   __ _ _ _ __
    *  | |    / _ \ / _` | | '_ \
    *  | |___| (_) | (_| | | | | |
    *  \_____/\___/ \__, |_|_| |_|
    *                __/ |
    *               |___/
    *
    * ************************************************************************************/
    assembleLoginRequest(userName, secret, subscriptionId, proprietaryInput) {
        return { providerCode: this.cloudProvider, username: userName, secret: secret }; // just a pass-thru - doesnt do anything special.
    }
    promptToLogin(options) {
        var _a, _b, _c, _d;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                let providerSubscriptionId = options === null || options === void 0 ? void 0 : options.providerSubscriptionId;
                let suppressConfirmations = options === null || options === void 0 ? void 0 : options.suppressConfirmations;
                let providedUserName = options === null || options === void 0 ? void 0 : options.providedUserName;
                let providedSecret = options === null || options === void 0 ? void 0 : options.providedSecret;
                let isAuthed = false;
                let cspUser = undefined;
                let userName = undefined;
                let secret = undefined;
                if (!suppressConfirmations) {
                    this._ui.userMessage(`Enter your credentials for ${this._styler.hilite(this.cloudProvider)}`);
                    userName = yield this._ui.prompt('regUsername', "Username (Hit enter if using a token):", false);
                    if (userName === undefined || userName === "")
                        userName = "<token>"; // TODO: make username nullable on the authPvd, so this becomes the job of the auth provider
                    secret = yield this._ui.promptPassword('regSecret', `Password (or token):`);
                }
                else {
                    if (!providedUserName || !providedSecret)
                        throw new Error("Must provide cloud provider username/pwd to login silent mode");
                    userName = providedUserName;
                    secret = providedSecret;
                }
                cspUser = {
                    tenantCode: this.codiacUser.tenantCode,
                    provider: this.cloudProvider,
                    username: userName,
                    subscriptionId: providerSubscriptionId,
                    created: new Date(Date.now())
                };
                try {
                    this._ui.startSpinner(`Authenticating with ${this.cloudProvider}...`);
                    // let authResult = await this.relayClient.logIntoCloudProvider(this.cloudProvider, { Username: userName, Secret: secret });
                    let authResult = yield this.relayClient.Call.csp_login({ providerCode: this.cloudProvider, username: userName, secret: secret });
                    if ((_a = authResult.output) === null || _a === void 0 ? void 0 : _a.cspUser)
                        cspUser = (_b = authResult.output) === null || _b === void 0 ? void 0 : _b.cspUser;
                    isAuthed = authResult.success == true && authResult.output != undefined;
                    this._ui.stopSpinner("Success!");
                }
                catch (err) {
                    this.logger.debug(`Error authenticating with ${this.cloudProvider}: ${(_c = err.name) !== null && _c !== void 0 ? _c : ""} ${(_d = err.message) !== null && _d !== void 0 ? _d : ""}`);
                    this._ui.stopSpinner("Failed.");
                }
                if (isAuthed)
                    this._ui.userMessage(`Logged into ${this._styler.hilite(this.cloudProvider)} as [${this._styler.hilite(userName !== null && userName !== void 0 ? userName : "token")}]`);
                // let subxId = await this.promptForSubscriptionId(userName, providerSubscriptionId);
                return [isAuthed, cspUser];
            }
            catch (err) {
                throw err;
            }
        });
    }
    promptToLogout(accountFilter) {
        var _a, _b, _c, _d, _e;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let req = {
                providerCode: this.cloudProvider,
                accountRef: accountFilter
            };
            let authResult = new contracts_2.SingleResult(false);
            try {
                this._ui.startSpinner(`Logging out of ${this.cloudProvider}...`);
                authResult = yield this.relayClient.Call.csp_logout(req); // we could just as easily call csp creds delete here, since we're not yet supporting an actual logout from aws, but lets leave that decision to the csp auth provider upstream.
                this._ui.stopSpinner("Success!");
                return [authResult.success, (_b = (_a = authResult.output) === null || _a === void 0 ? void 0 : _a.cspUserName) !== null && _b !== void 0 ? _b : ""]; // returns an empty string when no creds were stored.
            }
            catch (err) {
                this._ui.stopSpinner("Failed.");
                err.message = "Error logging out of ".concat(this.cloudProvider, ": ", (_e = (_c = err.message) !== null && _c !== void 0 ? _c : ((((_d = err.name) === null || _d === void 0 ? void 0 : _d.toLowerCase()) === "error") ? undefined : err.name)) !== null && _e !== void 0 ? _e : "(no details available)");
                this.logger.debug(err.message);
                throw err;
            }
        });
    }
};
HelmResourceConfigurator = tslib_1.__decorate([
    (0, inversify_1.injectable)(),
    tslib_1.__param(0, (0, inversify_1.inject)(codiac_ops_common_1.UserNameTenantCode)),
    tslib_1.__param(1, (0, inversify_1.inject)(codiac_relay_1.RelayClient)),
    tslib_1.__param(2, (0, inversify_1.inject)(ops_1.INTERFACES_CLI.IUserInputProvider)),
    tslib_1.__param(3, (0, inversify_1.inject)(ops_1.INTERFACES_CLI.IOutputStyler)),
    tslib_1.__param(4, (0, inversify_1.inject)(codiac_common_1.INTERFACES.IBetterLogger)),
    tslib_1.__metadata("design:paramtypes", [codiac_ops_common_1.UserNameTenantCode,
        codiac_relay_1.RelayClient, Object, Object, Object])
], HelmResourceConfigurator);
exports.HelmResourceConfigurator = HelmResourceConfigurator;
//# sourceMappingURL=helm-resource-configurator.js.map