"use strict";
var reporter_resolve_1 = require("./reporter.resolve");
var task_resolve_1 = require("./task.resolve");
var task_runner_1 = require("./task.runner");
var reports = require("./reporter.resolve");
var seq = require("./task.sequence");
var command_run_context_1 = require("./command.run.context");
var debug = require('debug')('cb:command.run.execute');
function executeRunCommand(runCommandSetup, report, config) {
    var tasks = runCommandSetup.tasks, sequence = runCommandSetup.sequence, runner = runCommandSetup.runner, cli = runCommandSetup.cli;
    /**
     * Get a run context for this execution.
     * note: This could take some time as it may need
     * to hash directories etc. A run context is just a key=>value
     * map of read-only values.
     */
    return command_run_context_1.default(tasks.all, config)
        .timestamp(config.scheduler)
        .flatMap(function (complete) {
        return run(complete.value, complete.timestamp);
    })
        .share();
    /**
     * Return the stream so a consumer can receive the RunCompletionReport
     */
    /**
     * Now actually execute the tasks.
     */
    function run(runContext, startTime) {
        /**
         * series/parallel running have VERY different characteristics
         * @type {Rx.Observable<TaskReport>|Rx.Observable<TaskReport>}
         */
        var mode = (function () {
            if (config.runMode === task_resolve_1.TaskRunModes.parallel) {
                return runner.parallel(runContext);
            }
            return runner.series(runContext);
        })();
        /**
         * Now add side effects
         */
        return mode
            .do(function (taskReport) {
            if (config.progress) {
                report({
                    type: reports.ReportTypes.TaskReport,
                    data: { taskReport: taskReport }
                });
            }
        })
            .toArray()
            .timestamp(config.scheduler)
            .map(function (complete) {
            /**
             * Merge sequence tree with Task Reports
             * to product stats.
             */
            var reports = complete.value;
            var decoratedSequence = seq.decorateSequenceWithReports(sequence, reports);
            return {
                sequence: decoratedSequence,
                runtime: complete.timestamp - startTime,
                cli: cli,
                config: config,
                taskErrors: reports.filter(function (x) { return x.type === task_runner_1.TaskReportType.error; })
            };
        })
            .do(function (completed) {
            report({
                type: reporter_resolve_1.ReportTypes.Summary,
                data: completed
            });
        });
    }
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = executeRunCommand;
//# sourceMappingURL=command.run.execute-cli.js.map