"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const YAML = require("yaml");
const command_base_enterprise_1 = require("../../command-base-enterprise");
const _ = require("lodash");
const render = require("../../uilogic/render-methods");
const render_methods_1 = require("../../uilogic/render-methods");
const type_safety_utils_1 = require("../../uilogic/type-safety-utils");
class SnapshotList extends command_base_enterprise_1.CommandBaseEnterprise {
    run() {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.bootstrap();
            const { args, flags } = yield this.parse(SnapshotList);
            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 currentEnterprise = (yield this.establishEnterpriseContext(rootMap, flags.enterprise, interactionMode)).enterprise;
                // RETRIEVE 
                let outputFormat = (_a = type_safety_utils_1.TypeSafetyUtils.toEnum(render_methods_1.OutputFormatsEnum, flags.output)) !== null && _a !== void 0 ? _a : render_methods_1.OutputFormatsEnum.tree;
                if ([render_methods_1.OutputFormatsEnum.json, render_methods_1.OutputFormatsEnum.yaml].includes(outputFormat) === false)
                    this._ui.startSpinner("Retrieving");
                // Filter by enterprise - API handles the filtering
                let crit = {
                    enterprise: currentEnterprise.name,
                    take: 20,
                    sort: "version~desc"
                };
                let result = yield this._codiacApi.EnterpriseVersionConfig.tryReadMany(crit);
                if (result.error) {
                    this.logger.error(`Error retrieving snapshots: ${result.error.message || result.message || "Unknown error"}`);
                    throw result.error;
                }
                let snapshots = (_b = result.output) !== null && _b !== void 0 ? _b : [];
                let snapshotCount = snapshots.length;
                if ([render_methods_1.OutputFormatsEnum.json, render_methods_1.OutputFormatsEnum.yaml].includes(outputFormat) === false)
                    this._ui.stopSpinner(`found ${snapshotCount}`);
                // RENDER
                let output = "";
                switch (outputFormat) {
                    case render_methods_1.OutputFormatsEnum.json:
                        // Keep full structure with contents array
                        let sortedForJson = _.sortBy(snapshots, s => s.enterprise, s => s.version);
                        output = JSON.stringify(sortedForJson, undefined, 2);
                        this._ui.userMessage(output);
                        break;
                    case render_methods_1.OutputFormatsEnum.yaml:
                        // Keep full structure with contents array
                        let sortedForYaml = _.sortBy(snapshots, s => s.enterprise, s => s.version);
                        output = YAML.stringify(sortedForYaml, { indent: 2 });
                        this._ui.userMessage(output);
                        break;
                    case render_methods_1.OutputFormatsEnum.text:
                        let listForText = this.buildSnapshotListForText(snapshots);
                        output = render.renderStringList(listForText);
                        this._ui.userMessage(output);
                        break;
                    case render_methods_1.OutputFormatsEnum.tree:
                    default:
                        let tree = this.buildSnapshotTree(snapshots);
                        let out = render.renderStringTree(tree);
                        this._ui.userMessage(out);
                        break;
                }
                return;
            }
            catch (err) {
                throw err;
            }
            finally {
                yield this.closeConnections();
            }
        });
    }
    buildSnapshotListForText(snapshots) {
        try {
            let listForText = [];
            let sorted = _.sortBy(snapshots, s => s.enterprise, s => s.version);
            for (let snapshot of sorted) {
                let snapshotLine = this._styler.hilite(snapshot.version);
                snapshotLine = snapshot.enterprise.concat("/", snapshotLine);
                let details = this.renderSnapshotDetails(snapshot);
                snapshotLine = snapshotLine.concat(this._styler.dim(` (${details})`));
                listForText.push(snapshotLine);
                // Add contents (assets) as indented sub-items
                if (snapshot.contents && Array.isArray(snapshot.contents) && snapshot.contents.length > 0) {
                    for (let content of snapshot.contents) {
                        let assetName = content.assetName || content.entityName || 'unknown';
                        let assetVersion = content.version || 'unknown';
                        let assetLine = `  └─ ${this._styler.hilite(assetName)} ${this._styler.dim(`(${assetVersion})`)}`;
                        listForText.push(assetLine);
                    }
                }
            }
            return listForText;
        }
        catch (err) {
            throw err;
        }
    }
    renderSnapshotDetails(snapshot) {
        let details = `created: ${this.formatDate(snapshot.created)}`;
        if (snapshot.contents && Array.isArray(snapshot.contents) && snapshot.contents.length > 0) {
            details = details.concat(`, ${snapshot.contents.length} asset${snapshot.contents.length !== 1 ? 's' : ''}`);
        }
        if (snapshot.contentHash) {
            details = details.concat(`, hash: ${snapshot.contentHash.substring(0, 8)}...`);
        }
        return details;
    }
    formatDate(date) {
        if (date instanceof Date) {
            return date.toISOString().split('T')[0];
        }
        return new Date(date).toISOString().split('T')[0];
    }
    buildSnapshotTree(snapshots) {
        let tree = [];
        let byEnterprise = _.groupBy(snapshots, s => s.enterprise);
        for (let enterprise of Object.keys(byEnterprise).sort()) {
            let entSnapshots = byEnterprise[enterprise];
            let entBranch = { text: `Enterprise: ${enterprise}` };
            for (let snapshot of _.sortBy(entSnapshots, s => s.version)) {
                let text = this._styler.hilite(snapshot.version);
                // Add asset count if available
                if (snapshot.contents && Array.isArray(snapshot.contents) && snapshot.contents.length > 0) {
                    text = text.concat(` (${snapshot.contents.length} asset${snapshot.contents.length !== 1 ? 's' : ''})`);
                }
                // Add created by
                text = text.concat(` - Tagged by: ${snapshot.createdBy}`);
                // Add creation date
                text = text.concat(` - Date: ${this.formatDate(snapshot.created)}`);
                let snapshotBranch = { text: text };
                // // Add contents (assets) as children
                // if (snapshot.contents && Array.isArray(snapshot.contents) && snapshot.contents.length > 0) {
                //   snapshotBranch.children = [];
                //   for (let content of snapshot.contents) {
                //     let assetName = (content as any).assetName || content.entityName || 'unknown';
                //     let assetVersion = content.version || 'unknown';
                //     let assetText = `${this._styler.hilite(assetName)} (${assetVersion})`;
                //     snapshotBranch.children.push({ text: assetText });
                //   }
                // }
                if (entBranch.children === undefined)
                    entBranch.children = [];
                entBranch.children.push(snapshotBranch);
            }
            tree.push(entBranch);
        }
        return tree;
    }
}
exports.default = SnapshotList;
SnapshotList.description = 'Shows the list of snapshots (enterprise version configs) in a given enterprise.';
SnapshotList.flags = {
    enterprise: core_1.Flags.string({ char: 'e', required: false, description: 'The name of the enterprise containing the snapshots being viewed (required if there are more than one).' }),
    output: core_1.Flags.string({ char: 'o', default: render_methods_1.OutputFormatsEnum.tree, description: "format in which to render the data.", options: [render_methods_1.OutputFormatsEnum.json, render_methods_1.OutputFormatsEnum.yaml, render_methods_1.OutputFormatsEnum.tree, render_methods_1.OutputFormatsEnum.text] }),
    help: core_1.Flags.help({ char: 'h', description: 'Displays the help document for this command.' })
};
SnapshotList.args = {};
//# sourceMappingURL=list.js.map