"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImageContextualizer = void 0;
const tslib_1 = require("tslib");
const inversify_1 = require("inversify");
const codiac_common_1 = require("@codiac.io/codiac-common");
const cli_common_1 = require("../cli-common");
const codiac_relay_1 = require("../apis/codiac-relay");
const ops_1 = require("../ops");
/** User interactions for selecting an image from a given container registry.
 */
let ImageContextualizer = class ImageContextualizer {
    constructor(_ui, _styler, relayClient, logger) {
        this._ui = _ui;
        this._styler = _styler;
        this.relayClient = relayClient;
        this.logger = logger;
    }
    promptForImage(registry, defaults) {
        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 img = Object.assign({ name: (_a = defaults.name) !== null && _a !== void 0 ? _a : "unnamed", registry: registry }, this.createAuditable());
                try {
                    // if (img.registry.type === undefined) throw new Error(`You must specify a registry before prompting for an image.`);
                    // let regClient = this.clientFactory.createForRegistry(registry);  // no need to authenticate - we just did that a few lines prior with the cloud pvd, and the same auth pvd should be injected along with its creds store client.
                    let imageFullName; // = defaults.name;
                    while (!imageFullName || imageFullName == "") {
                        // TODO: lets only get into the fuzzy search if they decide to change their selection
                        let fetcher = (searchString) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                                var _c, _d, _e, _f;
                                let output = [];
                                try {
                                    // let searchResult = await regClient.search({ query: searchString ?? "*" });
                                    let searchResult = yield this.relayClient.Call.searchRegistry({ registry: registry, searchString: searchString !== null && searchString !== void 0 ? searchString : "*" });
                                    if (searchResult.error) {
                                        output = [];
                                        throw searchResult.error;
                                    }
                                    else {
                                        output = (_d = (_c = searchResult.output) === null || _c === void 0 ? void 0 : _c.map(r => {
                                            var _a, _b;
                                            if (registry.provider == "dockerHub") {
                                                // BYG : Dockerhub changed how scope their images???
                                                //We have to carve out 'undefined' and add the orgCode if it's scoped
                                                r.name = r.name.replace("undefined/", "");
                                                r.scope = registry.organizationCode;
                                            }
                                            return {
                                                name: ((_b = (_a = r.scope) === null || _a === void 0 ? void 0 : _a.concat("/", r.name)) !== null && _b !== void 0 ? _b : r.name), value: r
                                            };
                                        })) !== null && _d !== void 0 ? _d : [];
                                    }
                                }
                                catch (err) {
                                    this.logger.error(`${(_e = err.name) !== null && _e !== void 0 ? _e : ''} ${(_f = err.message) !== null && _f !== void 0 ? _f : ''}`, err.stack);
                                    output = [];
                                }
                                finally {
                                    resolve(output);
                                }
                            }));
                        });
                        /** lets the remote server perform the fuzzy search
                         *  (instead of pulling all in one call then doing fuzzy locally. */
                        let fuzzyOnRemote = (_b = registry.useRemoteFiltering) !== null && _b !== void 0 ? _b : false; // This should be stored as !(registry.filterLocally ?? false)
                        let imageSelector = new cli_common_1.PromptSelectFuzzy(this.logger, this._ui, this._styler);
                        let selected = yield imageSelector.go('fullName', 'Select the container image for the asset:', false, imageFullName !== null && imageFullName !== void 0 ? imageFullName : defaults.name, fuzzyOnRemote, fetcher);
                        if (selected) {
                            imageFullName = selected.name;
                            img.name = selected.name;
                            if (selected.registry)
                                img.registry = Object.assign(Object.assign({}, selected.registry), this.createAuditable());
                        }
                    }
                }
                catch (err) {
                    this.logger.error(`${err.name} ${err.message}`, err.stack);
                }
                finally {
                    resolve(img);
                }
            }));
        });
    }
    createAuditable() {
        let stamp = new Date(Date.now());
        return {
            created: stamp,
            createdBy: "",
            modified: stamp,
            modifiedBy: ""
        };
    }
};
ImageContextualizer = tslib_1.__decorate([
    (0, inversify_1.injectable)(),
    tslib_1.__param(0, (0, inversify_1.inject)(ops_1.INTERFACES_CLI.IUserInputProvider)),
    tslib_1.__param(1, (0, inversify_1.inject)(ops_1.INTERFACES_CLI.IOutputStyler)),
    tslib_1.__param(2, (0, inversify_1.inject)(codiac_relay_1.RelayClient)),
    tslib_1.__param(3, (0, inversify_1.inject)(codiac_common_1.INTERFACES.IBetterLogger)),
    tslib_1.__metadata("design:paramtypes", [Object, Object, codiac_relay_1.RelayClient, Object])
], ImageContextualizer);
exports.ImageContextualizer = ImageContextualizer;
//# sourceMappingURL=image-contextualizer.js.map