"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceConfiguratorBase = void 0;
const tslib_1 = require("tslib");
const inversify_1 = require("inversify");
const _ = require("lodash");
const codiac_common_1 = require("@codiac.io/codiac-common");
const codiac_ops_common_1 = require("@codiac.io/codiac-ops-common");
const codiac_relay_1 = require("../../apis/codiac-relay");
const ops_1 = require("../../ops");
let ResourceConfiguratorBase = class ResourceConfiguratorBase {
    constructor(codiacUser, genRelayClient, _ui, _styler, logger) {
        this.codiacUser = codiacUser;
        this.genRelayClient = genRelayClient;
        this._ui = _ui;
        this._styler = _styler;
        this.logger = logger;
    }
    /** Applies defaults for this CSP */
    applyClusterDefaults(workingModel, initial, defaults) {
        var _a, _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let switchedCsp = Boolean(defaults !== undefined && (defaults.provider !== this.cloudProvider));
            if (defaults === undefined || (defaults.provider !== this.cloudProvider)) {
                let defaultResult = yield this.genRelayClient.Call.getClusterDefaults({ provider: this.cloudProvider });
                if (defaultResult.error) {
                    this.logger.warn(`Error retrieving defaults for ${this.cloudProvider} cluster: ${(_a = defaultResult.error.name) !== null && _a !== void 0 ? _a : ""} ${(_b = defaultResult.error.message) !== null && _b !== void 0 ? _b : ""}`);
                }
                defaults = (_c = defaultResult.output) !== null && _c !== void 0 ? _c : {}; // fall back to an empty object if we failed, so that we dont keep looking this up on subsequent calls.
                let assignment = (objVal, srcVal) => Boolean(srcVal === undefined) ? objVal : srcVal;
                if (switchedCsp) {
                    initial = _.assignWith({}, defaults, workingModel, { name: initial.name }, assignment); // Throw out any prior cluster properties bc they were set for a diff provider.
                }
                else {
                    initial = _.assignWith({}, defaults, initial, assignment);
                }
            }
            return [initial, defaults];
        });
    }
    promptForName(current) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let ultimate;
            let keepName = false;
            if (current != undefined && !_.isEmpty(current)) {
                // if (takeDefaults) {
                //   this._ui.userMessage("Cluster name: ".concat(this._styler.hilite(cluster.name)));
                // } else {
                keepName = yield this._ui.promptConfirm("nameConfirm", "Cluster name: ".concat(this._styler.hilite(current)), true);
                if (keepName)
                    ultimate = current;
                // }
            }
            if (!keepName || ultimate == undefined /* undef check is redundant, but its there for typescript */) {
                do {
                    ultimate = (yield this._ui.prompt("name", "Cluster name: ", true, current));
                } while (_.isEmpty(ultimate));
            }
            return ultimate;
        });
    }
    /** Asks the user whether to keep the default version, and if not presents a select list. */
    promptForK8sVersion(location, providerSubscription, defaultK8sVersion) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _a, _b;
                let output;
                try {
                    this._ui.startSpinner(`Loading K8s versions available in ${location} ...`);
                    let versResult = yield this.genRelayClient.Call.getAvailableK8sVersions({
                        provider: this.cloudProvider,
                        location: location,
                        subscriptionId: providerSubscription
                    });
                    if (versResult.error)
                        throw versResult.error;
                    let k8sVersions = (_b = (_a = versResult.output) === null || _a === void 0 ? void 0 : _a.map(x => x.k8sVersion)) !== null && _b !== void 0 ? _b : [];
                    this._ui.stopSpinner(`${k8sVersions.length} found`);
                    let keepVersion = false;
                    if (defaultK8sVersion && k8sVersions.indexOf(defaultK8sVersion) >= 0) {
                        keepVersion = yield this._ui.promptConfirm("keepVersion", `Kubernetes version: ${this._styler.hilite(defaultK8sVersion)} `);
                    }
                    if (keepVersion === true && defaultK8sVersion !== undefined) {
                        output = defaultK8sVersion;
                    }
                    else {
                        if (k8sVersions.length > 0) {
                            output = (yield this._ui.promptSelect("k8sVersion", "Kubernetes version: ", k8sVersions)); // defaults?.k8sVersion;
                        }
                        else {
                            output = (yield this._ui.prompt("k8sVersion", "Kubernetes version: ", true, defaultK8sVersion));
                        }
                    }
                    resolve(output);
                }
                catch (err) {
                    // this.logger.error(`${err.name ?? ''} ${err.message ?? ''}`, err.stack);
                    reject(err);
                }
            }));
        });
    }
    createAuditable() {
        let stamp = new Date(Date.now());
        return {
            created: stamp,
            createdBy: this.codiacUser.username,
            modified: stamp,
            modifiedBy: this.codiacUser.username
        };
    }
};
ResourceConfiguratorBase = 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])
], ResourceConfiguratorBase);
exports.ResourceConfiguratorBase = ResourceConfiguratorBase;
//# sourceMappingURL=resource-configurator-base.js.map