"use strict";
var Rx = require('rx');
var reports = require("./reporter.resolve");
var task_resolve_1 = require('./task.resolve');
var Immutable = require('immutable');
var command_run_setup_1 = require("./command.run.setup");
var command_run_interactive_1 = require("./command.run.interactive");
var command_run_execute_cli_1 = require("./command.run.execute-cli");
var debug = require('debug')('cb:command.run');
var _ = require('../lodash.custom');
(function (TriggerTypes) {
    TriggerTypes[TriggerTypes["command"] = "command"] = "command";
    TriggerTypes[TriggerTypes["watcher"] = "watcher"] = "watcher";
})(exports.TriggerTypes || (exports.TriggerTypes = {}));
var TriggerTypes = exports.TriggerTypes;
function handleIncomingRunCommand(cli, input, config, report) {
    /**
     * Array of top-level task names that are available
     */
    var topLevelTasks = Object.keys(input.tasks);
    /**
     * The shared Map that tasks can read/write to
     */
    var sharedMap = new Rx.BehaviorSubject(Immutable.Map({}));
    var type = TriggerTypes.command;
    debug('top level tasks available', topLevelTasks);
    /**
     * If the interactive flag was given (-i), always try
     * that first.
     */
    if (config.interactive) {
        return enterInteractive();
    }
    /**
     * If the user never provided a task then we either look
     * for a `default` task or enter interactive mode if possible
     * eg:
     *  $ crossbow run
     */
    if (cli.input.length === 1) {
        /**
         * First look if there's a 'default' task defined
         */
        if (hasDefaultTask()) {
            var cliMerged = _.merge({}, cli, { input: ['run', 'default'] });
            runFrom({
                shared: sharedMap,
                cli: cliMerged,
                input: input,
                config: config,
                type: TriggerTypes.command
            });
            return;
        }
        /**
         * If no default task was found above, enter interactive mode
         */
        return enterInteractive();
    }
    /**
     * Check if the provided input contains either
     * 'default' or 'default@p' etc
     */
    function hasDefaultTask() {
        if (task_resolve_1.maybeTaskNames(input.tasks, 'default').length) {
            return true;
        }
        if (input.tasks['default'] !== undefined) {
            return true;
        }
    }
    /**
     * If no task given, or if user has selected interactive mode,
     * show the UI for task selection
     */
    function enterInteractive() {
        /**
         * No top level tasks, so exit with the correct error
         */
        if (!topLevelTasks.length) {
            return report({ type: reports.ReportTypes.NoTasksAvailable });
        }
        /**
         * Now prompt for input
         */
        return command_run_interactive_1.default(cli, input, config)
            .subscribe(function (answers) {
            var cliMerged = _.merge({}, cli, { input: ['run'].concat(answers.tasks) });
            var configMerged = _.merge({}, config, { runMode: task_resolve_1.TaskRunModes.parallel });
            runFrom({
                shared: sharedMap,
                cli: cliMerged,
                input: input,
                config: configMerged,
                type: type
            });
        });
    }
    /**
     * If we reach here we're dealing with the default case
     * where we are simply executing the command as normal
     * eg:
     *  $ crossbow run task1 task2@p etc ...
     */
    runFrom({
        shared: sharedMap,
        cli: cli,
        input: input,
        config: config,
        type: type
    });
    /**
     * @param trigger
     * @returns {any}
     */
    function runFrom(trigger) {
        var setup = command_run_setup_1.getRunCommandSetup(trigger);
        if (setup.tasks.invalid.length) {
            report({
                type: reports.ReportTypes.TaskErrors,
                data: {
                    tasks: setup.tasks.invalid,
                    taskCollection: cli.input.slice(1),
                    input: trigger.input,
                    config: config
                }
            });
        }
        return command_run_execute_cli_1.default(setup, report, config)
            .subscribe(function (complete) {
            console.log(complete);
        }, function (err) {
            console.log(err);
        });
    }
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = handleIncomingRunCommand;
//# sourceMappingURL=command.run-cli.js.map