"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImageConfigurator = void 0;
const tslib_1 = require("tslib");
const path = require("path");
const _ = require("lodash");
const FileHound = require("filehound");
const codiac_ops_common_1 = require("@codiac.io/codiac-ops-common");
// Enterprise references... 
const codiac_relay_contracts_1 = require("@codiac.io/codiac-relay-contracts");
const ops_1 = require("../ops");
// /** Human-readable code for the provider of a container registry.  */
// export enum ImageRegistryProvidersEnum {
//   dockerhub = "dockerhub",
//   azure = "azure",
//   google = "google",
//   amazon = "amazon",
//   other = "other"
// }
/** Interactively guides the user through assembling a properly built image export definition.
 *
 */
class ImageConfigurator {
    static bootstrap(ioc) {
    }
    constructor(_tenantCode, _codiacApi, relayClient, _projCfg, _projUserCfg, ui, styler, _projectRoot, logger, credsStore, _userCntx) {
        this._tenantCode = _tenantCode;
        this._codiacApi = _codiacApi;
        this.relayClient = relayClient;
        this._projCfg = _projCfg;
        this._projUserCfg = _projUserCfg;
        this.ui = ui;
        this.styler = styler;
        this._projectRoot = _projectRoot;
        this.logger = logger;
        this.credsStore = credsStore;
        this._userCntx = _userCntx;
        this._cliExec = new codiac_ops_common_1.CliExec(logger);
        this.imageCount = 0;
        if (this._projCfg.images) {
            for (let imgName in this._projCfg.images) {
                this.imageCount++;
            }
        }
    }
    /**
     *
     * @param argsImageName
     * @param definitionFile
     * @param port
     * @param buildParams
     * @returns
     */
    createImage(argsImageName, definitionFile, port, buildParams) {
        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 model = { name: argsImageName };
                    if (definitionFile)
                        model.definitionFile = definitionFile;
                    if (port)
                        model.port = port;
                    let registry = yield this.selectRegistry();
                    model.targets = [registry];
                    if (!(yield this.credsStore.get(registry.registryUrl))) {
                        yield this.authenticateWith(registry.registryUrl);
                    }
                    let candidateScopeName = undefined;
                    model.name = argsImageName;
                    while (!model.name || model.name.includes(registry.registryUrl)) {
                        model.name = yield this.ui.prompt("imageName", "Image Name?", true, model.name);
                        if ((_a = model.name) === null || _a === void 0 ? void 0 : _a.includes("/")) {
                            const splitInput = model.name.split("/");
                            model.name = splitInput.pop();
                            candidateScopeName = splitInput.join("/");
                            while (candidateScopeName === null || candidateScopeName === void 0 ? void 0 : candidateScopeName.includes(registry.registryUrl)) {
                                this.ui.userMessage("Looks like you included the registry url");
                                candidateScopeName = yield this.ui.prompt("imageName", `Add a scope? (e.g ${this.styler.hilite("scope")}/${model.name})`, false, registry.username);
                            }
                        }
                        else {
                            candidateScopeName = yield this.ui.prompt("imageName", `Add a scope? (e.g ${this.styler.hilite("scope")}/${model.name})`, false /*, registry.username */);
                            if (candidateScopeName) {
                                while (candidateScopeName === null || candidateScopeName === void 0 ? void 0 : candidateScopeName.includes(registry.registryUrl)) {
                                    candidateScopeName = yield this.ui.prompt("imageName", `Scope should not be the same as your registry url (e.g ${this.styler.hilite("scope")}/${model.name})`, false, registry.username);
                                }
                                if (candidateScopeName === null || candidateScopeName === void 0 ? void 0 : candidateScopeName.includes("/")) {
                                    const splitInput = candidateScopeName.split("/");
                                    candidateScopeName = splitInput.join("/");
                                }
                            }
                        }
                    }
                    model.name = (candidateScopeName) ? `${candidateScopeName}/${model.name}` : model.name;
                    // TODO: set a required identity for this registry and scope
                    // if no scope in name, prompt for a scope (based on the registry type it may be named differently)
                    model.definitionFile = yield this.selectDefinitionFile(model.name, definitionFile);
                    // PERHAPS WE NEED TO TAKE THIS OUT.  
                    // Docker images themselves dont support an externally facing default port number.
                    // This is unique to codiac images, and only useful from within the project.
                    // IT WOULD BE NICE: to expose a config schema for an image.
                    model.port = port || (yield this.ui.prompt("port", "Default port number: ", false, port));
                    // Prompt for additional DOcker image build arguments
                    if (!buildParams) {
                        buildParams = [];
                        let entry = yield this.ui.prompt("buildParams", "Additional docker build command switches (as: arg=val) (enter for none): ", false);
                        while (entry && entry !== "") {
                            buildParams.push(entry);
                            entry = yield this.ui.prompt("buildParams", "Additional docker build command switches (as: arg=val) (enter for none): ", false);
                        }
                    }
                    console.log(buildParams.join("..."));
                    if (buildParams && buildParams.length > 0) {
                        model.buildParams = {};
                        for (let entry of buildParams) {
                            let delimPos = entry.indexOf("=");
                            let arg;
                            if (delimPos > 0) {
                                arg = entry.substring(0, delimPos);
                                model.buildParams[arg] = (delimPos + 1 == entry.length) ? "" : entry.substring(delimPos + 1);
                            }
                            else {
                                arg = entry;
                                model.buildParams[arg] = "";
                            }
                        }
                    }
                    let image = model;
                    console.log(`IMage buildParams: ` + JSON.stringify(image.buildParams));
                    resolve(image);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Walks user thru selection of a valid image definition file,
     * based on any existing files in the project
     * and preventing collisions with any definition files
     * that are already in use by other image exports.  */
    selectDefinitionFile(scopedImageName, requestedFile) {
        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 definitionFile;
                    // We need the in-use search for all cases
                    let projImages = []; // TODO:  Change this goddamn dictionary to an array.
                    for (let imgName in this._projCfg.images) {
                        projImages.push(this._projCfg.images[imgName]);
                    }
                    let inUse = projImages.filter(i => i.definitionFile != undefined).map(i => {
                        return path.relative(this._projectRoot, path.join(this._projectRoot, i.definitionFile)).toLowerCase();
                    });
                    if (!requestedFile || this.isInUse(requestedFile, inUse)) {
                        if (requestedFile) {
                            this.ui.userMessage(`${this.styler.colorCritical("INVALID")}: The image definition file [${requestedFile}] is already being used by another ImageExport.`);
                        }
                        // Gather up any existing image definition files in the project folder (recursive). 
                        let files = yield FileHound.create()
                            .path(this._projectRoot)
                            .glob("Dockerfile", "*.dockerfile")
                            .ignoreHiddenDirectories()
                            .discard("submodules|node_modules|dist|bin")
                            .find();
                        files = files.map(file => path.relative(this._projectRoot, file)); // This would be a nice flag to add to filehound, eg: .relativePath()
                        // Strip out any definition files that are already in use by existing ImageExports
                        let filesNotYetUsed = files;
                        if (inUse.length > 0)
                            filesNotYetUsed = files.filter(file => !this.isInUse(file, inUse));
                        // Prompt the user to select a valid filename
                        let selected;
                        let defaultFileName = this.buildDefaultDefinitionFileName(scopedImageName, [...inUse, ...filesNotYetUsed]);
                        // let choices: string[];
                        // choices = ["** none: automatic **", ...filesNotYetUsed, defaultFileName, ImageConfigurator.CHOICE_ENTER_MANUALLY]
                        let choices = [];
                        // choices.push({ name: "** none: automatic **", value: "" });
                        if (filesNotYetUsed && filesNotYetUsed.length > 0)
                            choices.push(...filesNotYetUsed.map(f => { return { name: f, value: f }; }));
                        choices.push({ name: defaultFileName, value: defaultFileName });
                        choices.push({ name: ImageConfigurator.CHOICE_ENTER_MANUALLY, value: ImageConfigurator.CHOICE_ENTER_MANUALLY });
                        choices = _.uniqBy(choices, c => c.name);
                        selected = yield this.ui.promptSelect("definitionFile", "Image definition file: ", choices);
                        // User wants to set their own unique filename 
                        while (selected == ImageConfigurator.CHOICE_ENTER_MANUALLY || (selected && this.isInUse(selected, inUse))) {
                            if (this.isInUse(selected, inUse)) {
                                this.ui.userMessage(`${this.styler.colorCritical("INVALID")}: The image definition file [${selected}] is already being used by another ImageExport.`);
                            }
                            selected = (yield this.ui.prompt("manualDefinitionFile", "Image definition file: ", true));
                        }
                        definitionFile = selected;
                    }
                    else {
                        definitionFile = requestedFile;
                    }
                    resolve(definitionFile);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /**
     * @param relPathName Relative path from the project root.
     * @param existingPathNames NOTE:  Must already be resolved and lowercased relative paths.
     */
    isInUse(relPathName, existingPathNames) {
        let resolvedRel = path.relative(this._projectRoot, path.join(this._projectRoot, relPathName)).toLowerCase();
        let exists = existingPathNames.indexOf(resolvedRel) >= 0;
        return (exists);
    }
    buildDefaultDefinitionFileName(scopedImageName, omit) {
        var _a;
        let file;
        // let existingDefs = [];
        // for (let imgName in this._projCfg.images) {
        //   let defnFile = this._projCfg.images[imgName].definitionFile || DxConstants.DEFAULT_DOCKERFILE_NAME;
        //   existingDefs.push(defnFile.toLowerCase());
        // }
        let bareImageName = (_a = _.last(scopedImageName.split("/"))) === null || _a === void 0 ? void 0 : _a.toLowerCase();
        let attempt = 0;
        while (!file || this.isInUse(file, omit)) {
            attempt++;
            switch (attempt) {
                case 1:
                    file = ops_1.DxConstants.DEFAULT_DOCKERFILE_NAME;
                    break;
                case 2:
                    file = `${bareImageName}.dockerfile`;
                    break;
                case 3:
                    // file =  `${bareImageName}-${attempt-1}.dockerfile`;
                    file = `${scopedImageName.replace("/", "--").toLowerCase()}.dockerfile`;
                default: // this case is pretty unlikely to happen (and besides, it's only a default we're generating here)
                    file = `${scopedImageName.replace("/", "--").toLowerCase()}-${attempt - 1}.dockerfile`;
            }
        }
        return file;
    }
    authenticateWith(registryDomain) {
        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, _c;
                try {
                    let success = false;
                    let pvdResult = yield this.relayClient.Call.getRegistryType({ registryUrl: registryDomain });
                    if (pvdResult.error)
                        throw pvdResult.error;
                    if (pvdResult.output == undefined)
                        throw new Error(`Did not recogize registry domain [${registryDomain}].`);
                    let pvdInfo = pvdResult.output;
                    // if (pvdInfo.provider == CloudProviderEnum.azure) {
                    //   let azAuth = new AzureAcrCliAuthenticator(this.ui, this.logger);
                    //   success = await azAuth.authenticate(registryDomain);
                    // } else {
                    let authenticated = false;
                    while (!authenticated) {
                        let defaultUsername = (this._userCntx) ? this._userCntx.userName : undefined;
                        let username = yield this.ui.prompt("registryUsername", `Credentials for [${registryDomain}] \n Username:  `, false, defaultUsername);
                        let secret = yield this.ui.promptPassword("registryPassword", `Password/AccessToken: `);
                        // let authResult = await client.authenticate(secret, username);  // this also writes to the credentials store.
                        let authResult = yield this.relayClient.Call.csp_login({ providerCode: pvdInfo.provider, username: username, secret: secret });
                        authenticated = authResult.success;
                        if (!authResult.success) {
                            let msg = `Authentication failed for image registry [${registryDomain}]: ${(_c = (_b = (_a = authResult.error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : authResult.message) !== null && _c !== void 0 ? _c : ""}`;
                            this.ui.userMessage(msg);
                            this.logger.debug(msg); //, authResult);
                        }
                    }
                    success = true;
                    // }
                    resolve(success);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    // private getProviderOf(registryDomain: string): ImageRegistryProvidersEnum {
    //   let parts = registryDomain.toLowerCase().split(".");
    //   if (parts.length > 2) {
    //     let lastTwo = [parts[parts.length - 2], parts[parts.length - 1]].join(".");
    //     switch (lastTwo) {
    //       case "docker.io":
    //         return ImageRegistryProvidersEnum.dockerhub;
    //       case "azurecr.io":
    //         return ImageRegistryProvidersEnum.azure;
    //       case "gcr.io":
    //         return ImageRegistryProvidersEnum.google;
    //       case "amazonaws.com":
    //         return ImageRegistryProvidersEnum.amazon;
    //     }
    //   }
    //   return ImageRegistryProvidersEnum.other;
    // }
    /** The goal is to present the user with a list of registries that are
     *  RELEVANT TO THE CURRENT PROJECT,
     *  so that the easiest path thru the UI is a valid one with minimal input.
     *  (an image misplaced into the wrong registry can have serious impact,
     *   especially for someone working against multiple tenants).
     *
     *  However, relevancy to a project is a moving target BECAUSE:
     *
     *  a) A codiac enterprise has the ability to pull images from ANY REGISTRY, as long as it has the creds to do so.
     *
     *  b) The tenant may not be defined yet at the time an image is defined.
     *
     *  c) The image project has only a loose affiliation with an enterprise (it's not an Asset project),
     *     so the current enterprise mapping can change from one moment to the next.
     *
     *  d) A tenant or an enterprise will tend to restrict its registries toa  short list,
     *     but it must have the ability to add images from other registries if needed.
     *
     *  e) Even though public registries (such as DockerHub) are always valid,
     *     they are often not RELEVANT for a given tenant or enterprise.
     *
     *  Thus...
     *
     *  The select list of image registries needs to be curated to account for:
     *  * The images in the PROJECT,
     *  * The registries favored by the TENANT,
     *  * The assets in the ENTERPRISE,
     *  * The registries of the current USER.
     *
     *
     * choices: if there are images in project, we use the registries from those images.
     * If the image has an enterprise binding, we use the registries from the existing enterprise (highlighted).
     * If we are logged into azure.
     *
     *  Scenario:  no images, no tenant, no enterprise or assets
     *    DefaultList: (DockerHub + az acr list + docker creds store list + **go find one**). Other leads to registry declaration workflow
     *
     *  Scenario: no images, tenant, no enterprise
     *    TenantDefaultList: (select distinct registries from all enterprise assets in all enterprises for tenant) + **other**
     *
     *  Scenario: no images, tenant, bound to enterprise, no assets
     *    DefaultList
     *
     *  Scenario: no images, bound to enterprise w assets
     *    EnterpriseDefaultList: Select distinct registries from asset images + **other** (other leads to DefaultList without existings)
     *
     *  Scenario: images exist, no enterprise
     *    LocalDefaultList: Just like enterprise list, but using local images instead of assets
     *
     *  Scenario: images exist, one or more enterprise bindings
     *    LocalDefaults + EnterpriseDefaults per binding
     *
     * **go find one** registry workflow: (assumes you’ve already chosen against docker hub)
     *  Registry Provider?
     *  ACR (Azure)
     *  Xyz (Aws)
     *  Pdq (Google)
     *  Custom (Must be a Docker registry instance)
     *  ---> Selection fires the applicable registry configurator
     *
     *  ACR:
     *  Use current account: mark.f@tb.onm.com (Y/n)?
     *  (Ensure az login, confirm current account)
     *  Azure Subscription? [Az account list]
     *  Acr?  [Az acr list --subscription asdf]
     *
     *  Custom Docker Registry
     *  Use current account
     *
     */
    selectRegistry() {
        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 firstList = yield this.gatherRelevantRegistries();
                    let choices = firstList.map(r => { return { name: r.registryUrl, value: r.registryUrl }; });
                    choices.push({ name: ImageConfigurator.CHOICE_OTHER, value: ImageConfigurator.CHOICE_OTHER });
                    // console.dir(choices);
                    // this.logger.trace(`registries: `, choices);
                    let reg = yield this.ui.promptSelect("registry", "Select a target registry...", choices);
                    // console.log(`Selected registry: ${reg}`);
                    let selected;
                    if (reg == ImageConfigurator.CHOICE_OTHER) {
                        let secondList = yield this.gatherAllRegistriesNotIn(firstList);
                        let newChoices = secondList.map(r => { return { name: r.registryUrl, value: r.registryUrl }; });
                        // MarkStartHere("add choices to get one from a different azure subscription (and other cloud providers")
                        newChoices.push({ name: ImageConfigurator.CHOICE_ENTER_MANUALLY, value: ImageConfigurator.CHOICE_ENTER_MANUALLY });
                        let otherReg = yield this.ui.promptSelect("registry", "Select a target registry...", newChoices);
                        if (otherReg == ImageConfigurator.CHOICE_ENTER_MANUALLY) {
                            let manual;
                            let confirmed = false;
                            while (!confirmed || !manual) {
                                manual = yield this.ui.prompt("otherRegistryDomain", "Enter registry domain:  ", true);
                                if (!manual)
                                    throw new Error(`Unable to create an image export without a registry url.`);
                                // TODO:  Validate this by searching instead of just asking for confirmation.
                                confirmed = yield this.ui.promptConfirm("otherRegistryDomainConfirm", `[${this.styler.hilite(manual)}] Is this correct ?  `);
                            }
                            selected = new codiac_relay_contracts_1.RegistryTarget("default", manual);
                        }
                        else {
                            selected = secondList.find(r => r.registryUrl == otherReg);
                        }
                    }
                    else {
                        selected = firstList.find(r => r.registryUrl == reg); // cant we make this the value?
                    }
                    resolve(selected);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    gatherAllRegistriesNotIn(excludes) {
        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 pubs = yield this.getPublicRegistries();
                    let stored = yield this.getRegistriesFromDockerCredsStore();
                    // TODO: Query for registries in all my az subscriptions
                    let pool = [...pubs, ...stored];
                    // Strip the reg url down to the domain name and sort the list
                    pool.forEach(r => r.registryUrl = codiac_ops_common_1.OpsUtils.extractDomainNameFrom(r.registryUrl).toLowerCase());
                    pool = pool.filter(r => !excludes.find(x => x.registryUrl == r.registryUrl));
                    pool = _.uniqBy(pool, r => r.registryUrl);
                    pool = _.sortBy(pool, r => r.registryUrl);
                    resolve(pool);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Puts together the list of registries that are relevant for the current project. */
    gatherRelevantRegistries() {
        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 pubs; //  = await this.getPublicRegistries();
                    let projs; //  = await this.getRegistriesFromProjectImages();
                    let stored; //  = await this.getRegistriesFromDockerCredsStore();
                    let tenant; //  = await this.getRegistriesFromTenant();
                    let pool = []; //  = [...pubs, ...projs, ...stored];
                    if (this.imageCount > 0) {
                        projs = yield this.getRegistriesFromProjectImages();
                        pool.push(...projs);
                    }
                    if (this._tenantCode === ops_1.DxConstants.UNREGISTERED_TENANT_CODE) {
                        if (this.imageCount == 0) {
                            pubs = yield this.getPublicRegistries();
                            stored = yield this.getRegistriesFromDockerCredsStore();
                            pool.push(...pubs, ...stored);
                        }
                    }
                    else {
                        if (this._projUserCfg.enterprise) {
                            tenant = yield this.getRegistriesFromTenantAssets(this._projUserCfg.enterprise.enterpriseCode);
                        }
                        else {
                            tenant = yield this.getRegistriesFromTenantAssets();
                        }
                        pool.push(...tenant);
                        if (tenant.length == 0) {
                            // + majors using tenant's cloud provider accounts  (We're not currently storing these subscriptions - but we need to be)
                        }
                        if (pool.length == 0) {
                            pubs = yield this.getPublicRegistries();
                            stored = yield this.getRegistriesFromDockerCredsStore();
                            pool.push(...pubs, ...stored);
                        }
                    }
                    // Strip the reg url down to the domain name and sort the list
                    pool.forEach(r => r.registryUrl = codiac_ops_common_1.OpsUtils.extractDomainNameFrom(r.registryUrl).toLowerCase());
                    pool = _.uniqBy(pool, r => r.registryUrl);
                    pool = _.sortBy(pool, r => r.registryUrl);
                    resolve(pool);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    getPublicRegistries() {
        let registries = [];
        // DOCKER HUB
        registries.push({ environment: "default", registryUrl: "index.docker.io" }); // docker hub 
        // Should we be using "hub.docker.io" instead?  
        // Or the full url "https://index.docker.io/v1" ?
        return registries;
    }
    /** Each of these registries requires an account with the given cloud provider,
     *  and in most cases a provisioning of a container registry to have been previously performed. */
    getRegistriesFromMajors(scope) {
        let registries = [];
        // AZURE (ACR)
        registries.push({ environment: "default", registryUrl: `${scope}.azurecr.io` });
        // GOOGLE (GCR)
        // gcr.io is the default and is locted in the united states (for now).
        // There are hostnames for continent, eg: us.gcr.io, asia.gcr.io, eu.gcr.io 
        // See https://cloud.google.com/container-registry/docs/overview
        let googleRegistryDomains = [
            `gcr.io`,
            `us.gcr.io`,
            `asia.gcr.io`,
            `eu.gcr.io`
        ];
        for (let regDomain of googleRegistryDomains) {
            registries.push({ environment: "default", registryUrl: `${regDomain}/${scope}` });
        }
        // AWS (ECR)
        // "...Each AWS account is provided with a single (default) Amazon ECR registry..."
        // See https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html
        // The URL for your default registry is: https://aws_account_id.dkr.ecr.region.amazonaws.com
        registries.push({ environment: "default", registryUrl: `${scope}.dkr.ecr.region.amazonaws.com` });
        return registries;
    }
    getRegistriesFromProjectImages() {
        let registries = [];
        if (this._projCfg.images) {
            for (let imgName in this._projCfg.images) {
                let img = this._projCfg.images[imgName];
                if (img.targets && img.targets.length > 0) {
                    registries.push(...img.targets);
                }
            }
        }
        return registries;
    }
    getRegistriesFromTenantAssets(enterpriseCode) {
        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 registries = [];
                    let crit = { all: true }; // this automatically filters by tenant
                    if (enterpriseCode)
                        crit.enterprise = enterpriseCode;
                    let projxn = { pathsIncluded: ["name", "image"], pathsExcluded: [] };
                    let readResult = yield this._codiacApi.Asset.tryReadMany(crit, { projection: projxn });
                    if (readResult.error)
                        throw readResult.error;
                    if (readResult.output && readResult.output.length > 0) {
                        let fromAssets = readResult.output.map(ass => new codiac_relay_contracts_1.RegistryTarget("default", ass.image.registry.url, undefined, undefined, ass.image.registry.infoUrl));
                        registries.push(...fromAssets);
                    }
                    resolve(registries);
                }
                catch (err) {
                    this.logger.error(`Error [${err.name}] getting registries from tenant assets: ${err.message}`, err);
                    reject(err);
                }
            }));
        });
    }
    getRegistriesFromDockerCredsStore() {
        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 registries = [];
                    let creds = yield this.credsStore.list();
                    if (creds) {
                        // NOTE:  We cannot guarantee that the credsId is going to be the registryUrl - in fact, it's not even likely anymore bc creds are going to be stored per cloud provider, not per registry.  
                        registries = creds.map(c => new codiac_relay_contracts_1.RegistryTarget("default", c.credsId, c.Username)); // used to add the secret here
                    }
                    resolve(registries);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
}
exports.ImageConfigurator = ImageConfigurator;
ImageConfigurator.CHOICE_OTHER = "** Other **";
ImageConfigurator.CHOICE_ENTER_MANUALLY = "** Enter one manually **";
//# sourceMappingURL=image-configurator.js.map