import {ICommand} from "./ICommand";
import {IChallengeProvider} from "../challenges/IChallengeProvider";
import {OptParserUtil} from "./OptParserUtil";
import {IConsoleFormatter} from "../console/IConsoleFormatter";
import commander = require('commander');

export class ListCommand implements ICommand {
    constructor(protected challengeProvider: IChallengeProvider,
                protected consoleFormatter: IConsoleFormatter) {
    }

    /**
     * reddit-dp ls|list
     *     Lists all challenges
     *
     * @param program
     * @returns {ICommand}
     */
    register(program: commander.ICommand): commander.ICommand {
        return program
            .command('ls')
            .alias('list')
            .description('print information about all available challenges')
            .option('-d, --difficulty [difficulty]', 'filter for difficulty (3=hard,2=intermediate,1=easy)')
            .option('-l, --limit [limit]', 'limit results (default=25)')
            .action((program: commander.ICommand) => {
                let difficulty = OptParserUtil.parseDifficulty(program['difficulty']);

                // console.log(difficulty, difficulty != null && isFinite(difficulty))
                return this.challengeProvider.getAll(difficulty)
                    .then(challenges => challenges
                        .slice(0, program['limit'] || 25)
                        .reverse()
                    )
                    .then(challenges => {
                        let std = this.consoleFormatter.format(challenges, true, [ "id", "difficulty", "title" ]);
                        process.stdout.write(std);
                        process.exit();
                    });
            });
    }
}