"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PROMPT_ME_DESIGNATOR = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const _ = require("lodash");
const contracts_1 = require("@codiac.io/codiac-common/contracts");
const command_base_enterprise_1 = require("../../../command-base-enterprise");
// const { selectFiles, COMPLETED, CANCELLED } = require('select-files-cli');  // gd js wo ts...
// const { selectFiles, COMPLETED, CANCELLED } = require('../../uilogic/file-selector');  // gd js wo ts...
/** The value provided as input that indicates
 * a user's desire to be prompted with a list from which choose the value(s),
 * instead of entering them manually or taking a default. */
exports.PROMPT_ME_DESIGNATOR = "?";
class AssetVolumeDelete extends command_base_enterprise_1.CommandBaseEnterprise {
    run() {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.bootstrap();
            const { args, flags } = yield this.parse(AssetVolumeDelete);
            (_a = this._relayContainer) === null || _a === void 0 ? void 0 : _a.ready$.subscribe((ready) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                var _b;
                try {
                    this._userCntx = yield this.establishTenantContext(this._userCntx);
                    let rootMap = yield this.getRootMap();
                    const interactionMode = this.getInteractionMode(flags.silent, flags.echo, flags['to-script']);
                    let enterprise = (yield this.establishEnterpriseContext(rootMap, flags.enterprise, interactionMode)).enterprise;
                    _.remove(rootMap.enterprises, e => e.name != enterprise.name); // trim down to match legacy conditions
                    let aCntx = yield this.establishAssetContext(enterprise, true);
                    let asset = enterprise.assets.find(a => a.name == aCntx[0]);
                    if (!asset.reservedFolders || asset.reservedFolders.length == 0) {
                        this._ui.userMessage(`Asset [${asset.name}] in enteprise [${enterprise}] has no volume mounts defined.`);
                        this._ui.userMessage(`No work was done.`);
                    }
                    else {
                        let folderRes;
                        // Silent mode (throws if invalid)
                        if (flags.silent) {
                            if (!flags.name) {
                                throw new Error(`No name was provided for the volume mount.`);
                            }
                            folderRes = (_b = asset.reservedFolders) === null || _b === void 0 ? void 0 : _b.find(f => f.name == flags.name);
                            if (!folderRes) {
                                throw new Error(`No volume mount named [${flags.name}] is declared in asset [${asset.name}] in enterprise [${asset.enterprise}].`);
                            }
                        }
                        else {
                            let confirmed = false;
                            while (!confirmed || !folderRes) {
                                let choices = asset.reservedFolders.map(f => { return { name: `${f.name} (${f.path})`, value: f.name }; });
                                let selected = (yield this._ui.promptSelect("mountName", "Choose the volume mount to delete: ", choices, false));
                                folderRes = asset.reservedFolders.find(f => f.name == selected); // <--- guaranteed match
                                confirmed = yield this._ui.promptConfirm("confirm", `Delete Volume Mount [${this._styler.bold(folderRes.name)} (${folderRes.path})] from Asset [${asset.name}]?`, false);
                            }
                        }
                        let resultPatch = yield this.deleteVolumeMountFromAsset(enterprise.name, asset, folderRes);
                        if (resultPatch.success) {
                            this.logger.notice(`Successfully deleted volume mount [${folderRes.name}] with path [${folderRes.path}] from asset [${asset.enterprise}/${asset.name}]`);
                            this._ui.userMessage(`Successfully deleted volume mount [${folderRes.name}] with path [${folderRes.path}] from asset [${asset.enterprise}/${asset.name}]`);
                        }
                        else if (resultPatch.error) {
                            this.logger.error(`Error deleting volume mount [${folderRes.name}] with path [${folderRes.path}] from asset [${asset.enterprise}/${asset.name}]: ${resultPatch.message || ""}; ${resultPatch.error.message || resultPatch.error.stack}`);
                            this._ui.userMessage(`Error deleting volume mount [${folderRes.name}] with path [${folderRes.path}] from asset [${asset.enterprise}/${asset.name}]: ${resultPatch.message || ""}; ${resultPatch.error.message || resultPatch.error.stack}`);
                        }
                        else {
                            this.logger.warn(`Failed without error to delete volume mount [${folderRes.name}] with path [${folderRes.path}] from asset [${asset.enterprise}/${asset.name}]: ${resultPatch.message || ""}`);
                            this._ui.userMessage(`Failed without error to delete volume mount [${folderRes.name}] with path [${folderRes.path}] from asset [${asset.enterprise}/${asset.name}]: ${resultPatch.message || ""}`);
                        }
                    }
                }
                catch (err) {
                    this.handleError(err);
                }
                finally {
                    yield this.closeConnections();
                    return;
                }
            }));
        });
    }
    deleteVolumeMountFromAsset(enterprise, asset, folderRes) {
        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 result = new contracts_1.SingleResult(false);
                try {
                    if (asset.reservedFolders && asset.reservedFolders.length > 0) {
                        _.remove(asset.reservedFolders, f => f.name == folderRes.name);
                        if (asset.reservedFolders.length > 0) {
                            asset.reservedFolders = _.sortBy(asset.reservedFolders, f => f.path);
                        }
                        else {
                            delete asset.reservedFolders;
                        }
                        // let ops: patchOperation[] = [];
                        // ops.push(new patchOperation(patchOperationType.remove, "reservedFolders", folderRes));  // removes the given element from the reservedFolders array (how does it do the match?)
                        // let patch = new PatchSpecForOne(asset.id!, ops);
                        // result = await this._codiacApi.Asset.tryPatch(patch);
                        // OR we could do this instead - this would be more idempotent
                        this.logger.trace("Asset update", asset);
                        result = yield this._codiacApi.Asset.tryUpdate(asset);
                    }
                }
                catch (err) {
                    result.message = `Error updating asset ${asset.name}: ${err.message}`;
                    result.error = err;
                }
                finally {
                    resolve(result);
                }
            }));
        });
    }
}
exports.default = AssetVolumeDelete;
AssetVolumeDelete.description = 'Deletes an existing volume mount in the asset';
AssetVolumeDelete.aliases = ['asset:vol:delete', 'asset:volumes:delete', 'asset:volume:del', 'asset:vol:del', 'asset:volumes:del'];
AssetVolumeDelete.dependsOn = ["name"];
AssetVolumeDelete.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    name: core_1.Flags.string({ char: 'n', required: false, description: "Moniker for identifying, retrieving, and accessing this folder mapping.  Must be unique for the asset." }),
    enterprise: core_1.Flags.string({ char: 'e', description: '(required only if more than one enterprise exists) The name of the enterprise to which the asset belongs.' }),
    silent: core_1.Flags.boolean({ char: 'y', dependsOn: AssetVolumeDelete.dependsOn, required: false, description: `(Optional: defaults to false) Prevents confirmations of user-values that are remembered from prior runs. Requires: ${AssetVolumeDelete.dependsOn}` })
};
//# sourceMappingURL=delete.js.map