"use strict";
var command_run_1 = require('./command.run');
var task_resolve_1 = require('./task.resolve');
var task_list_1 = require("./reporters/task.list");
var Rx = require('rx');
var reporter_resolve_1 = require("./reporter.resolve");
var file_utils_1 = require("./file.utils");
function execute(trigger) {
    var input = trigger.input, config = trigger.config, reporter = trigger.reporter;
    /**
     * Either resolve ALL tasks, or a subset if given
     * via the cli.
     *
     * eg:
     *      crossbow ls -> all tasks
     *      crossbow ls build-all -> only build all tasks
     */
    var toResolve = (function () {
        /**
         * First look if there's trailing task names in cli input
         * @type {string[]}
         */
        var cliTasks = trigger.cli.input.slice(1);
        if (cliTasks.length) {
            return cliTasks;
        }
        /**
         * Now build up available tasks using input + tasks directories
         */
        var taskNamesToResolve = Object.keys(input.tasks);
        var taskNamesFromTasksDir = file_utils_1.getPossibleTasksFromDirectories(config.tasksDir, config.cwd);
        return taskNamesToResolve.concat(taskNamesFromTasksDir);
    })();
    /**
     * Resolve the subset
     * @type {Tasks}
     */
    var resolved = task_resolve_1.resolveTasks(toResolve, trigger);
    /**
     * handoff if requested
     */
    if (trigger.config.handoff) {
        return Rx.Observable.just({ tasks: resolved, errors: [] });
    }
    /**
     * If no tasks were matched, give the usual error
     */
    if (resolved.all.length === 0) {
        reporter({ type: reporter_resolve_1.ReportTypes.NoTasksAvailable });
        return Rx.Observable.just({ tasks: resolved, errors: [] });
    }
    /**
     * If any were invalid or if the user gave the verbose
     * flag, show the full tree
     */
    if (resolved.invalid.length || config.verbose === 1 /* Verbose */) {
        reporter({
            type: reporter_resolve_1.ReportTypes.TaskTree,
            data: {
                tasks: resolved.all,
                config: config,
                title: 'Available tasks:'
            }
        });
    }
    else {
        /**
         * Otherwise just print a simple two-col list
         */
        reporter({
            type: reporter_resolve_1.ReportTypes.SimpleTaskList,
            data: {
                lines: task_list_1.getSimpleTaskList(resolved.valid)
            }
        });
    }
    return Rx.Observable.just({ tasks: resolved, errors: [] });
}
function handleIncomingTasksCommand(cli, input, config, reporter) {
    return execute({
        cli: cli,
        input: input,
        config: config,
        reporter: reporter,
        type: command_run_1.TriggerTypes.command
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = handleIncomingTasksCommand;
//# sourceMappingURL=command.tasks.js.map