import { Command, flags as Flags } from '@heroku-cli/command';
import { color, hux } from '@heroku/heroku-cli-util';
import { ux } from '@oclif/core/ux';
import { getGeneration } from '../../lib/apps/generation.js';
export default class Index extends Command {
    static description = 'list available spaces';
    static flags = {
        json: Flags.boolean({ description: 'output in json format' }),
        team: Flags.team(),
    };
    static topic = 'spaces';
    display(spaces) {
        /* eslint-disable perfectionist/sort-objects */
        hux.table(spaces, {
            Name: { get: space => color.space(space.name) },
            Team: { get: space => color.team(space.team.name || '') },
            Region: { get: space => space.region.name },
            State: {
                get(space) {
                    if (space.state === 'allocated')
                        return color.success(space.state);
                    if (space.state === 'deleting')
                        return color.failure(space.state);
                    return color.warning(space.state);
                },
            },
            Generation: { get: space => getGeneration(space) },
            createdAt: {
                header: 'Created At',
                get: space => space.created_at,
            },
        });
        /* eslint-enable perfectionist/sort-objects */
    }
    displayJSON(spaces) {
        ux.stdout(JSON.stringify(spaces, null, 2));
    }
    async run() {
        const { flags } = await this.parse(Index);
        const { json, team } = flags;
        let { body: spaces } = await this.heroku.get('/spaces', {
            headers: {
                Accept: 'application/vnd.heroku+json; version=3.sdk',
            },
        });
        if (team) {
            spaces = spaces.filter(s => s.team.name === team);
        }
        spaces = this.sortByName(spaces);
        if (json)
            this.displayJSON(spaces);
        else if (spaces.length === 0) {
            if (team)
                ux.error(`No spaces in ${color.team(team)}.`);
            else
                ux.error('You do not have access to any spaces.');
        }
        else {
            this.display(spaces);
        }
    }
    sortByName(spaces) {
        spaces.sort((a, b) => a.name === b.name ? 0 : (a.name < b.name ? -1 : 1));
        return spaces;
    }
}
