"use strict";
var task_sequence_factories_1 = require("../task.sequence.factories");
var task_resolve_1 = require("../task.resolve");
var taskErrors = require("../task.errors");
var watchErrors = require("../watch.errors");
var logger_1 = require("../logger");
var path_1 = require("path");
var watch_resolve_1 = require("../watch.resolve");
var task_resolve_2 = require("../task.resolve");
var task_runner_1 = require("../task.runner");
var task_sequence_1 = require("../task.sequence");
var task_utils_1 = require("../task.utils");
var task_list_1 = require("./task.list");
var reporter_resolve_1 = require("../reporter.resolve");
var l = logger_1.default.info;
var baseUrl = 'http://crossbow-cli.io/docs/errors';
var archy = require('archy');
var parsed = path_1.parse(__dirname);
var depsDir = path_1.join(path_1.dirname(parsed.dir), 'node_modules');
function nl() {
    // logger.info('');
}
/**
 * There are multiple ways to output trees to the screen,
 * so this helper function helps to normalize the output
 * by providing the same padding on all but the first line.
 */
function multiLineTree(tree) {
    var split = tree.split('\n');
    logger_1.default.info(split[0]);
    split.slice(1, -1).forEach(function (line) {
        logger_1.default.unprefixed('info', "   " + line);
    });
}
exports.multiLineTree = multiLineTree;
/**
 * Accept any string and output each line as though
 * logger.info was called for each line (to maintain prefixes etc)
 */
function multiLine(input) {
    input.split('\n')
        .forEach(function (line) {
        logger_1.default.info(line);
    });
}
exports.multiLine = multiLine;
/**
 * Summary is a sequence tree with stats overlaid
 */
function reportSummary(sequence, cli, title, config, runtime) {
    var errorCount = task_sequence_1.countSequenceErrors(sequence);
    var skipCount = task_sequence_1.collectSkippedTasks(sequence, []);
    // todo - show a reduced tree showing only errors
    if (config.verbose === 1 /* Verbose */ || errorCount > 0) {
        var cliInput = cli.input.slice(1).map(function (x) { return ("'" + x + "'"); }).join(' ');
        nl();
        reportSequenceTree(sequence, config, "+ Results from " + cliInput, true);
    }
    logger_1.default.info('{gray:--------}');
    if (errorCount > 0) {
        nl();
        cli.input.slice(1).forEach(function (input) {
            var match = getSequenceItemThatMatchesCliInput(sequence, input);
            var errors = task_sequence_1.countSequenceErrors(match);
            if (errors > 0) {
                l("{red:x} input: {yellow:" + input + "} caused an error");
            }
        });
        nl();
        if (config.fail) {
            l("{red:x} " + title + " {yellow:" + duration(runtime) + " (" + errorCount + " %s)", errorCount === 1 ? 'error' : 'errors');
        }
        else {
            l("{yellow:x} " + title + " {yellow:" + duration(runtime) + " (" + errorCount + " %s)", errorCount === 1 ? 'error' : 'errors');
        }
    }
    else {
        nl();
        if (skipCount.length > 0) {
            l("{ok: } " + title + " {yellow:" + duration(runtime) + "} (" + skipCount.length + " skipped item" + (skipCount.length === 1 ? '' : 's') + ", use -f to force)");
        }
        else {
            l("{ok: } " + title + " {yellow:" + duration(runtime));
        }
    }
    logger_1.default.info('{gray:--------}');
}
function _taskReport(report) {
    var skipped = report.item.task.skipped || report.stats.skipped;
    var item = report.item;
    var label = task_utils_1.escapeNewLines((function () {
        if (item.subTaskName) {
            return item.task.taskName + ":{bold:" + item.subTaskName + "}";
        }
        if (item.viaName) {
            if (item.viaName.indexOf(':') > -1) {
                var split = item.viaName.split(':');
                return split[0] + ":{bold:" + split[1] + "}";
            }
            return item.viaName;
        }
        return item.task.rawInput;
    })());
    switch (report.type) {
        case task_runner_1.TaskReportType.start:
            if (skipped) {
                l("{yellow:-} " + label + " {yellow:(skipped)}");
            }
            else {
                l("{yellow:>} " + label);
            }
            break;
        case task_runner_1.TaskReportType.end:
            if (skipped) {
                return;
            }
            l("{green:\u2714} " + label + " {yellow:(" + duration(report.stats.duration) + ")}");
            break;
        case task_runner_1.TaskReportType.error:
            l("{red:x} " + label);
            break;
    }
}
function getSequenceItemThatMatchesCliInput(sequence, input) {
    return sequence.filter(function (item) {
        if (item.taskName) {
            if (item.taskName === input) {
                return true;
            }
        }
        else {
            return item.task.rawInput === input;
        }
    });
}
function getTaskCollectionList(taskCollection) {
    return taskCollection.map(incomingTaskItemAsString);
}
function incomingTaskItemAsString(x) {
    if (typeof x === 'string') {
        return task_utils_1._e(x);
    }
    if (typeof x === 'function') {
        if (x.name) {
            return "[Function: " + x.name + "]";
        }
        return '[Function]';
    }
}
function reportTaskList(sequence, cli, titlePrefix, config) {
    if (titlePrefix === void 0) { titlePrefix = ''; }
    if (config.verbose === 1 /* Verbose */) {
        var cliInput = cli.input.slice(1).map(function (x) { return ("'" + x + "'"); }).join(' ');
        nl();
        reportSequenceTree(sequence, config, "+ Task Tree for " + cliInput);
    }
    else {
        l('{yellow:+}%s {bold:%s}', titlePrefix, cli.input.slice(1).join(', '));
    }
}
function reportBeforeTaskList(sequence, cli, config) {
    l('{yellow:+} %s {bold:%s}', 'Before tasks for watcher:', cli.input.join(', '));
    if (config.verbose === 1 /* Verbose */) {
        var cliInput = cli.input.map(function (x) { return ("'" + x + "'"); }).join(' ');
        nl();
        reportSequenceTree(sequence, config, "+ Task Tree for " + cliInput);
        nl();
    }
}
function reportBeforeTasksDidNotComplete(error) {
    l('{red:x} %s', error.message);
    l('  so none of the watchers started');
}
function getWatcherNode(watcher) {
    var tasksString = (function () {
        return watcher.tasks.map(incomingTaskItemAsString).join(', ');
    })();
    return [
        ("{bold:Patterns:} {cyan:" + watcher.patterns.map(function (x) { return task_utils_1._e(x); }).join(', ') + "}"),
        ("{bold:Tasks:} {cyan:" + tasksString + "}"),
    ].join('\n');
}
function reportTaskErrors(tasks, taskCollection, input, config) {
    l('{gray.bold:------------------------------------------------}');
    l('{err: } Sorry, there were errors resolving your tasks,');
    l('  So none of them were run.');
    l('{gray.bold:------------------------------------------------}');
    taskCollection.forEach(function (n, i) {
        reportTaskTree([tasks[i]], config, "+ input: '" + n + "'");
    });
}
function reportWatchTaskTasksErrors(tasks, runner, config) {
    if (runner._tasks.invalid.length) {
        l('{gray.bold:---------------------------------------------------}');
        l("{err: } Sorry, there were errors when resolving the tasks");
        l("  that will be used in the following watcher");
        logWatcher(runner);
        reportTaskTree(tasks, config, "+ input: " + runner.parent);
    }
    else {
        l('{gray.bold:---------------------------------------------------}');
        l("{ok: } No errors from");
        logWatcher(runner);
        if (config.verbose === 1 /* Verbose */) {
            reportTaskTree(tasks, config, "+ input: " + runner.parent);
        }
    }
}
function logWatcher(runner) {
    l("  {bold:Watcher name:} {cyan:" + runner.parent + "}");
    l("      {bold:Patterns:} {cyan:" + runner.patterns.join(', ') + "}");
    l("         {bold:Tasks:} {cyan:" + runner.tasks.join(', ') + "}");
}
function logWatcherNames(runners, trigger) {
    logger_1.default.info('{yellow:Available Watchers:}');
    if (trigger.config.verbose === 0 /* Short */) {
        task_list_1.twoColWatchers(runners).forEach(function (x) { return logger_1.default.info(x[0] + " " + x[1]); });
        return;
    }
    runners.valid.forEach(function (runner) {
        logger_1.default.info("Name:  {bold:" + runner.parent + "}");
        logger_1.default.info('Files: ' + runner.patterns.map(task_utils_1._e).map(function (x) { return ("{cyan:" + x + "}"); }).join(', '));
        logger_1.default.info("Tasks: " + runner.tasks.map(function (x) { return ("{magenta:" + x + "}"); }).join(', '));
        logger_1.default.info('');
    });
    logger_1.default.info("Run your watchers in the following way:");
    logger_1.default.info("");
    runners.valid.forEach(function (runner) {
        logger_1.default.info(" {gray:$} crossbow watch {bold:" + runner.parent + "}");
    });
    if (runners.valid.length > 1) {
        logger_1.default.info('');
        logger_1.default.info('Or run multiple watchers at once, such as:');
        logger_1.default.info("");
        logger_1.default.info(' {gray:$} crossbow watch ' + runners.valid.slice(0, 2).map(function (x) { return ("{bold:" + x.parent + "}"); }).join(' '));
        logger_1.default.info('');
    }
}
function reportBeforeWatchTaskErrors(watchTasks, trigger) {
    l('{err: } Sorry, there were errors resolving your {red:`before`} tasks');
    l('  So none of them were run, and no watchers have begun either.');
    watchTasks.all.forEach(function (watchTask) {
        var cliInput = watch_resolve_1.resolveBeforeTasks(trigger.config.before, trigger.input, [watchTask]);
        var tasks = task_resolve_2.resolveTasks(cliInput, trigger);
        if (!tasks.all.length) {
            return;
        }
        if (trigger.config.verbose === 1 /* Verbose */) {
            return reportTaskTree(tasks.all, trigger.config, "+ Tasks to run before: '" + watchTask.name + "'");
        }
        if (tasks.invalid.length) {
            return reportTaskTree(tasks.all, trigger.config, "+ Tasks to run before: '" + watchTask.name + "'");
        }
    });
}
function logWatchErrors(tasks) {
    var errorCount = tasks.reduce(function (acc, item) {
        return acc + item.errors.length;
    }, 0);
    tasks.forEach(function (task) {
        if (task.errors.length) {
            logger_1.default.info("{red.bold:x '" + task.name + "'}");
            multiLine(getWatchError(task.errors[0], task));
        }
        else {
            logger_1.default.info("{ok: } '" + task.name + "'}");
        }
    });
    errorSummary(errorCount);
}
function errorSummary(errorCount) {
    if (errorCount) {
        l("{red:x} " + errorCount + " %s found (see above)", errorCount === 1 ? 'error' : 'errors');
    }
    else {
        l("{ok: } 0 errors found");
    }
}
function reportNoTasksProvided() {
    heading("Entering interactive mode as you didn't provide a task to run");
}
function heading(title) {
    l("" + title);
}
function getErrorText(sequenceLabel, stats, err, config) {
    if (!err.stack) {
        return err.toString();
    }
    /**
     * If _cbError is on the error object, it's a crossbow-generated
     * error so we handle it as though we know what we're doing
     */
    if (err._cbError) {
        return [
            ("{red.bold:x} {red:" + sequenceLabel + "} {yellow:(" + duration(stats.duration) + ")}"),
            task_utils_1.__e(err.stack)
        ].join('\n');
    }
    /**
     * At this point we have no idea what type the error is, so
     * the following code just makes the first line red and then
     * processes the stack traces (to remove internals)
     */
    var head = [
        ("{red.bold:x} " + sequenceLabel + " {yellow:(" + duration(stats.duration) + ")}"),
        ("{red.bold:" + err.stack.split('\n').slice(0, 1) + "}")
    ];
    var body = err.stack.split('\n').slice(1);
    var stack = getStack(body, config);
    var tail = "- Please see above for any output that may of occurred";
    if (!stack) {
        return head.concat([tail]).join('\n');
    }
    return head.concat(stack, [tail]).join('\n');
}
function getStack(stack, config) {
    /**
     * An array of string that can be compared
     * against each line of the stack trace to determine
     * if that line should be stipped. EG: we
     * don't want to muddy up stack traces with internals
     * from Rx/Immutable etc.
     */
    var stringMatches = (function () {
        if (config.debug)
            return [];
        return [
            parsed.dir,
            depsDir,
            'at bound (domain.js',
            'at runBound (domain.js'
        ];
    })();
    return stack
        .filter(function (line) {
        return stringMatches.every(function (string) {
            return line.indexOf(string) === -1;
        });
    });
}
exports.getStack = getStack;
/**
 * Add meta info to a sequence item suing the stats.
 * eg:
 *   @npm webpack -w
 * ->
 *   ✔ @npm webpack -w (14.2s)
 */
function appendStatsToSequenceLabel(label, stats, config) {
    /**
     * If any errors occured, append the error to the
     * label so it shows in the correct part of the tree
     */
    if (stats.errors.length) {
        var err = stats.errors[0];
        return getErrorText(label, stats, err, config);
    }
    /**
     * If this item was skipped, there cannot be anything to append
     */
    if (stats.skipped) {
        return "{yellow:-} " + label + " {yellow:(skipped)}";
    }
    /**
     * the item did not start if `started` is falsey
     */
    if (!stats.started) {
        return "{yellow:x} " + label + " {yellow:(didn't start)}";
    }
    /**
     * 'completed' means this task emitted a completion report.
     */
    if (stats.completed) {
        return "{green:\u2714} " + label + (" {yellow:(" + duration(stats.duration) + ")}");
    }
    /**
     * At this point, the task DID start, but the completed
     * flag is absent so we assume it was halted mid-flight.
     */
    return "{yellow:x} " + label + (" {yellow:(didn't complete, " + duration(stats.duration) + ")}");
}
/**
 * Show a tree of function calls
 */
function reportSequenceTree(sequence, config, title, showStats) {
    if (showStats === void 0) { showStats = false; }
    var toLog = getItems(sequence, []);
    var o = archy({ label: "{yellow:" + title + "}", nodes: toLog });
    multiLineTree(o);
    function getItems(items, initial) {
        return items.reduce(function (acc, item) {
            var label = getSequenceLabel(item, config);
            var stats = item.stats;
            if (showStats && item.type === task_sequence_factories_1.SequenceItemTypes.Task) {
                label = appendStatsToSequenceLabel(label, item.stats, config);
            }
            var nodes = getItems(item.items, []);
            return acc.concat({
                label: label,
                nodes: nodes
            });
        }, initial);
    }
}
exports.reportSequenceTree = reportSequenceTree;
function getSequenceLabel(item, config) {
    /**
     * Get the sequence label for a runnable task
     */
    if (item.type === task_sequence_factories_1.SequenceItemTypes.Task) {
        var baseName_1 = (function () {
            // if (item.viaName) {
            //     return `${item.task.taskName} via {bold:${item.viaName}}`;
            // }
            if (item.subTaskName) {
                if (item.fnName) {
                    return item.task.taskName + " [Function: {bold:" + item.fnName + "}] with config {bold:" + item.subTaskName + "}";
                }
                else {
                    return item.task.taskName + " with config {bold:" + item.subTaskName + "}";
                }
            }
            if (item.task.type === task_resolve_1.TaskTypes.InlineFunction) {
                return item.task.rawInput + " " + task_utils_1.getFunctionName(item.task.inlineFunctions[0]);
            }
            if (item.task.type === task_resolve_1.TaskTypes.ExternalTask) {
                return "" + item.task.rawInput;
            }
            if (item.task.type === task_resolve_1.TaskTypes.Adaptor) {
                return "" + item.task.rawInput;
            }
            if (item.task.externalTasks.length) {
                return moduleLabel(item.task);
            }
            return item.task.taskName;
        })();
        return baseName_1;
    }
    var baseName = (function () {
        /**
         * Here we are dealing with a ParallelGroup or a SeriesGroup
         */
        if (item.items.length === 1) {
            /**
             * Don't append 'series' or 'parallel' if this group
             * only consists of 1 item
             */
            if (item.subTaskName) {
                return logger_1.compile("{bold:" + item.taskName + ":" + item.subTaskName + "}");
            }
            return logger_1.compile("{bold:" + item.taskName + "}");
        }
        var typeLabel = (function () {
            if (item.type === task_sequence_factories_1.SequenceItemTypes.ParallelGroup) {
                return '<parallel>';
            }
            return '<series>';
        })();
        return logger_1.compile("{bold:" + item.taskName + "} " + typeLabel);
    })();
    if (item.skipped) {
        baseName += ' {yellow:(skipped)}';
    }
    if (item.stats && item.stats.skipped) {
        baseName += ' {yellow:(skipped)}';
    }
    return baseName;
}
function reportTaskTree(tasks, config, title) {
    var errorCount = 0;
    var toLog = getTasks(tasks, [], 0);
    var archy = require('archy');
    var output = archy({ label: "{yellow:" + title + "}", nodes: toLog });
    multiLineTree(output);
    errorSummary(errorCount);
    function getTasks(tasks, initial, depth) {
        return tasks.reduce(function (acc, task) {
            var errors = getErrors(task);
            if (errors.length) {
                errorCount += errors.length;
            }
            /**
             * Never show internal tasks at top-level
             */
            if (depth === 0) {
                if (task_utils_1.isInternal(task.rawInput)) {
                    return acc;
                }
            }
            var nodes = getTasks(task.tasks, [], depth++);
            var label = [getLabel(task)].concat(errors).join('\n');
            if (config.verbose === 1 /* Verbose */) {
                return acc.concat({
                    label: label,
                    nodes: nodes
                });
            }
            if (task.type === task_resolve_1.TaskTypes.Adaptor ||
                task.type === task_resolve_1.TaskTypes.ExternalTask) {
                if (task.errors.length) {
                    return acc.concat({
                        label: label,
                        nodes: []
                    });
                }
                return acc;
            }
            return acc.concat({
                label: label,
                nodes: nodes
            });
        }, initial);
    }
}
exports.reportTaskTree = reportTaskTree;
function getErrors(task) {
    if (!task.errors.length) {
        return [];
    }
    if (task.errors[0].type === taskErrors.TaskErrorTypes.TaskNotFound) {
        return [getSingleError(task.errors[0], task)];
    }
    return task.errors.map(function (error) { return getSingleError(error, task); });
}
exports.getErrors = getErrors;
function getSingleError(error, task) {
    return getExternalError(taskErrors.TaskErrorTypes[error.type], error, task);
}
function getWatchError(error, task) {
    return getExternalError(watchErrors.WatchTaskErrorTypes[error.type], error, task);
}
function getExternalError(type, error, val2) {
    return [
        logger_1.compile("{red:-} {bold:Error Type:}  " + type)
    ].concat(require('./error.' + type).apply(null, [error, val2]), [
        logger_1.compile("{red:-} {bold:Documentation}: {underline:" + baseUrl + "/{bold.underline:" + type + "}}"),
    ]).join('\n');
}
function moduleLabel(task) {
    var filepath = path_1.relative(process.cwd(), task.externalTasks[0].rawInput);
    if (task.taskName === filepath) {
        return "" + task.taskName;
    }
    return task.taskName + " " + filepath;
}
function npmScriptLabel(task) {
    return "{magenta:[npm script]} " + task.command;
}
function getLabel(task) {
    if (task.type === task_resolve_1.TaskTypes.InlineFunction) {
        var fnName = (function () {
            if (task.inlineFunctions[0].name !== '') {
                return "[Function: " + task.inlineFunctions[0].name + "]";
            }
            return '[Function]';
        })();
        return maybeErrorLabel(task, task.taskName + " " + fnName);
    }
    if (task.origin === task_resolve_1.TaskOriginTypes.NpmScripts) {
        return npmScriptLabel(task);
    }
    if (task.type === task_resolve_1.TaskTypes.TaskGroup) {
        if (task.errors.length) {
            return "{red.bold:x " + task.taskName + "}";
        }
        return "{bold:" + task.taskName + "}";
    }
    if (task.type === task_resolve_1.TaskTypes.ExternalTask) {
        return maybeErrorLabel(task, task.taskName);
    }
    if (task.type === task_resolve_1.TaskTypes.Adaptor) {
        return maybeErrorLabel(task, task.rawInput);
    }
    if (task.errors.length) {
        return "{red.bold:x " + task.taskName + "}";
    }
    return task.taskName + "}";
}
exports.getLabel = getLabel;
function maybeErrorLabel(task, label) {
    if (task.errors.length) {
        return "{red.bold:x " + label + "}";
    }
    return label;
}
function duration(ms) {
    return String((Number(ms) / 1000).toFixed(2)) + 's';
}
var reporterFunctions = (_a = {},
    _a[reporter_resolve_1.ReportNames.UsingConfigFile] = function (inputs) {
        inputs.forEach(function (input) {
            logger_1.default.info("Using: {cyan.bold:" + input.relative + "}");
        });
    },
    _a[reporter_resolve_1.ReportNames.InputFileNotFound] = function (inputs) {
        heading("Sorry, there were errors resolving your input files");
        inputs.forEach(function (item) {
            logger_1.default.info("{red.bold:x " + item.rawInput + "}");
            multiLine(getExternalError(item.errors[0].type, item.errors[0], item));
        });
    },
    _a[reporter_resolve_1.ReportNames.InvalidReporter] = function (reporters) {
        heading("{red.bold:x} Sorry, there were problems resolving your reporters");
        reporters.invalid.forEach(function (reporter) {
            reporter.errors.forEach(function (err) {
                if (err.type === reporter_resolve_1.ReporterErrorTypes.ReporterFileNotFound) {
                    heading("{red.bold:x " + err.file.resolved);
                    multiLine(getExternalError(err.type, err));
                }
                if (err.type === reporter_resolve_1.ReporterErrorTypes.ReporterTypeNotSupported) {
                    multiLine(getExternalError(err.type, err));
                }
            });
        });
    },
    _a[reporter_resolve_1.ReportNames.DuplicateConfigFile] = function (error) {
        heading("Sorry, this would cause an existing file to be overwritten");
        logger_1.default.info("{red.bold:x " + error.file.rawInput + "}");
        multiLine(getExternalError(error.type, error, error.file));
    },
    _a[reporter_resolve_1.ReportNames.ConfigFileCreated] = function (parsed) {
        multiLine("{green:\u2714} Created file: {cyan.bold:" + parsed.base + "}\n \nNow, try the `{yellow:hello-world}` example in that file by running: \n \n  {gray:$} crossbow run {bold:hello-world} \n \nOr to see multiple tasks running, with some in parallel, try: \n\n  {gray:$} crossbow run {bold:all}");
    },
    _a[reporter_resolve_1.ReportNames.InitConfigTypeNotSupported] = function (error) {
        heading("Sorry, the type {cyan.bold:" + error.providedType + "} is not currently supported");
        logger_1.default.info("{red.bold:x '" + error.providedType + "'}");
        multiLine(getExternalError(error.type, error));
    },
    _a[reporter_resolve_1.ReportNames.SimpleTaskList] = function (lines) {
        logger_1.default.info('{yellow:Available Tasks:');
        lines.forEach(function (line) { return logger_1.default.info(line); });
    },
    _a[reporter_resolve_1.ReportNames.TaskTree] = reportTaskTree,
    _a[reporter_resolve_1.ReportNames.TaskList] = reportTaskList,
    _a[reporter_resolve_1.ReportNames.TaskErrors] = reportTaskErrors,
    _a[reporter_resolve_1.ReportNames.TaskReport] = function (report, trigger) {
        if (trigger.config.progress) {
            _taskReport(report);
        }
    },
    _a[reporter_resolve_1.ReportNames.InvalidTasksSimple] = function (tasks) {
        logger_1.default.info('{red.bold:x Invalid tasks');
        logger_1.default.info('Sorry, we cannot generate documentation for you right now');
        logger_1.default.info('as you have invalid tasks. Please run {bold:$ crossbow tasks} to see');
        logger_1.default.info('details about these errors');
    },
    _a[reporter_resolve_1.ReportNames.NoTasksAvailable] = function () {
        heading('Sorry, there were no tasks available.');
        logger_1.default.info("{red.bold:x Input: ''}");
        multiLine(getExternalError(task_utils_1.InputErrorTypes.NoTasksAvailable, {}));
    },
    _a[reporter_resolve_1.ReportNames.NoTasksProvided] = reportNoTasksProvided,
    _a[reporter_resolve_1.ReportNames.BeforeWatchTaskErrors] = reportBeforeWatchTaskErrors,
    _a[reporter_resolve_1.ReportNames.BeforeTaskList] = reportBeforeTaskList,
    _a[reporter_resolve_1.ReportNames.BeforeTasksDidNotComplete] = reportBeforeTasksDidNotComplete,
    _a[reporter_resolve_1.ReportNames.WatchTaskTasksErrors] = reportWatchTaskTasksErrors,
    _a[reporter_resolve_1.ReportNames.WatchTaskErrors] = function (tasks) {
        heading("Sorry, there were errors resolving your watch tasks");
        logWatchErrors(tasks);
    },
    _a[reporter_resolve_1.ReportNames.WatchTaskReport] = function (report, trigger) {
        _taskReport(report);
    },
    _a[reporter_resolve_1.ReportNames.NoWatchersAvailable] = function () {
        heading('Sorry, there were no watchers available to run');
        logger_1.default.info("{red.bold:x No watchers available}");
        multiLine(getExternalError(task_utils_1.InputErrorTypes.NoWatchersAvailable, {}));
    },
    _a[reporter_resolve_1.ReportNames.NoWatchTasksProvided] = function () {
        heading("Entering interactive mode as you didn't provide a watcher to run");
    },
    _a[reporter_resolve_1.ReportNames.Watchers] = function (watchTasks) {
        nl();
        l("{yellow:+} Watching...");
        watchTasks.forEach(function (watchTask) {
            var o = archy({
                label: "{yellow:+ input: '" + watchTask.name + "'}", nodes: watchTask.watchers.map(getWatcherNode)
            });
            multiLineTree(o);
        });
    },
    _a[reporter_resolve_1.ReportNames.WatcherNames] = logWatcherNames,
    _a[reporter_resolve_1.ReportNames.NoFilesMatched] = function (watcher) {
        l('{red:x warning} `{cyan:%s}` did not match any files', watcher.patterns.join(' '));
    },
    _a[reporter_resolve_1.ReportNames.WatcherTriggeredTasks] = function (index, taskCollection) {
        l("{yellow:+} [" + index + "] " + getTaskCollectionList(taskCollection).join(', '));
    },
    _a[reporter_resolve_1.ReportNames.WatcherTriggeredTasksCompleted] = function (index, taskCollection, time) {
        l("{green:\u2714} [" + index + "] " + getTaskCollectionList(taskCollection).join(', ') + " {yellow:(" + duration(time) + ")}");
    },
    _a[reporter_resolve_1.ReportNames.DocsGenerated] = function docsGenerated(tasks, markdown) {
        // Todo - should we always output to the console?
        // l(`{green:✔} Documentation generated - copy/paste the following markdown into a readme.md file`);
        // console.log(markdown);
    },
    _a[reporter_resolve_1.ReportNames.DocsInputFileNotFound] = function (error) {
        heading("Sorry, there were errors resolving your input files");
        logger_1.default.info("{red.bold:x '" + error.file.resolved + "'}");
        multiLine(getExternalError(error.type, error));
    },
    _a[reporter_resolve_1.ReportNames.DocsAddedToFile] = function (file, content) {
        logger_1.default.info("{green:\u2714} Docs added to: {cyan.bold:" + file.relative + "}");
    },
    _a[reporter_resolve_1.ReportNames.DocsOutputFileExists] = function (error) {
        logger_1.default.info("{red.bold:x '" + error.file.resolved + "'}");
        multiLine(getExternalError(error.type, error));
    },
    _a[reporter_resolve_1.ReportNames.Summary] = reportSummary,
    _a[reporter_resolve_1.ReportNames.HashDirError] = function (error, cwd) {
        // const message = error.toString();
        logger_1.default.info("{red.bold:x CB-History hash failed} (tasks will still run)");
        multiLine(getExternalError(error.type, error, cwd));
    },
    _a
);
function default_1(name) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    if (typeof reporterFunctions[name] === 'function') {
        return reporterFunctions[name].apply(null, args);
    }
    console.log("Reporter not defined for '" + name + "' Please implement this method");
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
var _a;
//# sourceMappingURL=defaultReporter.js.map