"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImageRegistryContextualizer = void 0;
const tslib_1 = require("tslib");
const codiac_common_1 = require("@codiac.io/codiac-common");
const inversify_1 = require("inversify");
const codiac_relay_1 = require("../apis/codiac-relay");
const codiac_constants_1 = require("../codiac-constants");
const cloud_provider_contextualizer_1 = require("./cloud-provider-contextualizer");
const cloud_resource_configurator_factory_1 = require("./cloud-resource-configurator-factory");
const ops_1 = require("../ops");
/**
 *
 */
let ImageRegistryContextualizer = class ImageRegistryContextualizer {
    constructor(_uiCloudProvider, _codiacApi, relayClient, _ui, _styler, logger) {
        this._uiCloudProvider = _uiCloudProvider;
        this._codiacApi = _codiacApi;
        this.relayClient = relayClient;
        this._ui = _ui;
        this._styler = _styler;
        this.logger = logger;
        // this._uiCloudProvider = {} as CloudProviderContextualizer;
    }
    // private _uiCloudProvider: CloudProviderContextualizer;
    // private __uiCloudProvider_backing: CloudProviderContextualizer | undefined;
    // private get _uiCloudProvider(): CloudProviderContextualizer {
    //   if (this.__uiCloudProvider_backing === undefined) {
    //     this.__uiCloudProvider_backing = this.ioc.get(CloudProviderContextualizer);
    //   }
    //   return this.__uiCloudProvider_backing;
    // }
    /** Selection of an EITHER:
     *  a) existing registry definition,
     *  b) a selector for a built-in registry type,
     *  c) manual entry of a registry url
     */
    promptForRegistry(packageType, ioc, defaults, captureOnly = false) {
        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;
                try {
                    let registry;
                    // TODO:  Consider : if the defaults exists, show them the default and promptConfirm.  If they confirm no, then initiate the sequence below...
                    // SELECT EXISTING
                    if (captureOnly !== true) {
                        registry = yield this.promptForExistingRegistry(packageType);
                    }
                    if (registry !== undefined) {
                        let providerSubscriptionId = (_a = registry.accountId) !== null && _a !== void 0 ? _a : registry.subscriptionId;
                        yield this._uiCloudProvider.promptForCloudProviderCreds(ioc, registry.provider, undefined, undefined, undefined, providerSubscriptionId);
                    }
                    else { // DECLARE NEW
                        // 1. Select a cloud resource provider
                        let pvdResult = yield this.relayClient.Call.getRegistryProviders({});
                        if (pvdResult.error)
                            throw pvdResult.error;
                        if (pvdResult.output == undefined || pvdResult.output.length === 0)
                            throw new Error("There are currently no supported registry providers.");
                        let choices = pvdResult.output.map(x => x);
                        let provider = yield this._uiCloudProvider.promptForCloudProvider(choices, defaults.provider);
                        // 2. Authenticate with the cloud resource provider
                        const cspUser = yield this._uiCloudProvider.promptForCloudProviderCreds(ioc, provider);
                        // 3. Select a registry
                        let factory = new cloud_resource_configurator_factory_1.RegistryConfiguratorFactory(); //this._codiacApi, this._ui, this.logger);
                        let regCfg = factory.create(provider, ioc);
                        registry = yield regCfg.captureImageRegistry(cspUser.subscriptionId);
                    }
                    resolve(registry); //{ registry: registry, client: regClient })
                }
                catch (err) {
                    this.logger.error(`${err.name} ${err.message}`, err.stack);
                    reject(err);
                }
            }));
        });
    }
    /** Allows the user to OPTIONALLY select a registry that this tenant has already captured. */
    promptForExistingRegistry(packageType, includeOptionToCapture = true, registries) {
        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;
                try {
                    let registry;
                    0;
                    let selected = codiac_constants_1.CliConstants.PROMPT_ME_DESIGNATOR;
                    let crit; // we need a helm or not custom filter
                    crit = { all: true, packageType: packageType };
                    let existing = registries;
                    if (registries === undefined) {
                        let resultExisting = yield this._codiacApi.ImageRegistry.tryReadMany(crit);
                        if (resultExisting.success && resultExisting.output && ((_a = resultExisting.output) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                            existing = resultExisting.output;
                        }
                    }
                    if (existing && existing.length > 0) {
                        let choices = existing.map(r => { return { name: r.provider.concat(" ", this._styler.bold(r.code), " ", this._styler.dim(`(${r.url})`)), value: r.code }; });
                        if (includeOptionToCapture === true) {
                            choices.push({ name: "** other **", value: codiac_constants_1.CliConstants.PROMPT_ME_DESIGNATOR });
                        }
                        selected = (_b = yield this._ui.promptSelect("registry", "Container Registry:", choices)) !== null && _b !== void 0 ? _b : codiac_constants_1.CliConstants.PROMPT_ME_DESIGNATOR;
                        if (selected !== codiac_constants_1.CliConstants.PROMPT_ME_DESIGNATOR) {
                            registry = existing.find(r => r.code === selected);
                        }
                    }
                    resolve(registry);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    // ========================================================================================================
    // 
    // HELM
    // 
    // ========================================================================================================
    /** Selection of an EITHER:
   *  a) existing registry definition,
   *  b) a selector for a built-in registry type,
   *  c) manual entry of a registry url
   */
    promptForHelmRepository(packageType, ioc, defaults, captureOnly = false) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let registry;
                    // TODO:  Consider : if the defaults exists, show them the default and promptConfirm.  If they confirm no, then initiate the sequence below...
                    // SELECT EXISTING
                    if (captureOnly !== true) {
                        registry = yield this.promptForExistingRegistry(packageType);
                    }
                    if (registry !== undefined) {
                        yield this._uiCloudProvider.promptForCloudProviderCreds(ioc, registry.provider);
                    }
                    else { // DECLARE NEW
                        // 1. Select a cloud resource provider
                        let pvdResult = yield this.relayClient.Call.getRegistryProviders({});
                        if (pvdResult.error)
                            throw pvdResult.error;
                        if (pvdResult.output == undefined || pvdResult.output.length === 0)
                            throw new Error("There are currently no supported registry providers.");
                        let choices = pvdResult.output.map(x => x);
                        let provider = yield this._uiCloudProvider.promptForCloudProvider(choices, defaults.provider);
                        // 2. Authenticate with the cloud resource provider
                        yield this._uiCloudProvider.promptForCloudProviderCreds(ioc, provider);
                        // user/pass
                        // ------------------------------------------------------------------------------------------
                        // select tenant + subx
                        // refreshToken?
                        // 3. Select a registry
                        let factory = new cloud_resource_configurator_factory_1.RegistryConfiguratorFactory(); //this._codiacApi, this._ui, this.logger);
                        let regCfg = factory.create(provider, ioc);
                        registry = yield regCfg.captureImageRegistry();
                    }
                    resolve(registry); //{ registry: registry, client: regClient })
                }
                catch (err) {
                    this.logger.error(`${err.name} ${err.message}`, err.stack);
                    reject(err);
                }
            }));
        });
    }
};
ImageRegistryContextualizer = tslib_1.__decorate([
    (0, inversify_1.injectable)(),
    tslib_1.__param(0, (0, inversify_1.inject)(cloud_provider_contextualizer_1.CloudProviderContextualizer)),
    tslib_1.__param(1, (0, inversify_1.inject)(cloud_resource_configurator_factory_1.INTERFACES_CLI_ENTERPRISE.ICodiacClient)),
    tslib_1.__param(2, (0, inversify_1.inject)(codiac_relay_1.RelayClient)),
    tslib_1.__param(3, (0, inversify_1.inject)(ops_1.INTERFACES_CLI.IUserInputProvider)),
    tslib_1.__param(4, (0, inversify_1.inject)(ops_1.INTERFACES_CLI.IOutputStyler)),
    tslib_1.__param(5, (0, inversify_1.inject)(codiac_common_1.INTERFACES.IBetterLogger)),
    tslib_1.__metadata("design:paramtypes", [cloud_provider_contextualizer_1.CloudProviderContextualizer, Object, codiac_relay_1.RelayClient, Object, Object, Object])
], ImageRegistryContextualizer);
exports.ImageRegistryContextualizer = ImageRegistryContextualizer;
//# sourceMappingURL=image-registry-contextualizer.js.map