var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "charm", "./Reporter", "./Coverage", "istanbul-lib-coverage", "../common/util"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var charm = require("charm");
    var Reporter_1 = require("./Reporter");
    var Coverage_1 = require("./Coverage");
    var istanbul_lib_coverage_1 = require("istanbul-lib-coverage");
    var util_1 = require("../common/util");
    var eventHandler = Reporter_1.createEventHandler();
    var Runner = (function (_super) {
        __extends(Runner, _super);
        function Runner(executor, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this, executor, options) || this;
            _this.hidePassed = options.hidePassed || false;
            _this.hideSkipped = options.hideSkipped || false;
            _this.sessions = {};
            _this.hasRunErrors = false;
            _this.hasSuiteErrors = false;
            _this.serveOnly = executor.config.serveOnly;
            _this.charm = charm();
            _this.charm.pipe(_this.output);
            _this.charm.display('reset');
            _this._deprecationMessages = {};
            return _this;
        }
        Runner.prototype.coverage = function (message) {
            var session = this.sessions[message.sessionId || ''];
            session.coverage = session.coverage || istanbul_lib_coverage_1.createCoverageMap();
            session.coverage.merge(message.coverage);
        };
        Runner.prototype.deprecated = function (message) {
            // Keep track of deprecation messages we've seen before
            var key = message.original + "|" + message.replacement + "|" + message.message;
            if (this._deprecationMessages[key]) {
                return;
            }
            this._deprecationMessages[key] = true;
            this.charm
                .foreground('yellow')
                .write('⚠︎ ' + message.original + ' is deprecated. ');
            if (message.replacement) {
                this.charm.write('Use ' + message.replacement + ' instead.');
            }
            else {
                this.charm.write('Please open a ticket at https://github.com/theintern/intern/issues if you still ' +
                    'require access to this function.');
            }
            if (message.message) {
                this.charm.write(' ' + message.message);
            }
            this.charm.write('\n');
            this.charm.display('reset');
        };
        Runner.prototype.error = function (error) {
            this.charm.foreground('red');
            this.charm.write('(ノಠ益ಠ)ノ彡┻━┻\n');
            this.charm.write(this.formatError(error));
            this.charm.display('reset');
            this.charm.write('\n\n');
            this.hasRunErrors = true;
        };
        Runner.prototype.warning = function (warning) {
            this.charm.foreground('yellow');
            var message = typeof warning === 'string' ? warning : this.formatError(warning);
            this.charm.write("WARNING: " + message.replace(/^Error:\s+/, ''));
            this.charm.display('reset');
            this.charm.write('\n\n');
        };
        Runner.prototype.log = function (message) {
            var _this = this;
            message.split('\n').forEach(function (line) {
                _this.console.log("DEBUG: " + line);
            });
        };
        Runner.prototype.runEnd = function () {
            var _this = this;
            var map = istanbul_lib_coverage_1.createCoverageMap();
            var numTests = 0;
            var numFailedTests = 0;
            var numSkippedTests = 0;
            var sessionIds = Object.keys(this.sessions);
            var numEnvironments = sessionIds.length;
            if (sessionIds.length > 1) {
                sessionIds.forEach(function (sessionId) {
                    var session = _this.sessions[sessionId];
                    if (session.coverage) {
                        map.merge(session.coverage);
                    }
                    numTests += session.suite.numTests;
                    numFailedTests += session.suite.numFailedTests;
                    numSkippedTests += session.suite.numSkippedTests;
                });
                var charm_1 = this.charm;
                if (map.files().length > 0) {
                    charm_1.write('\n');
                    charm_1.display('bright');
                    charm_1.write('Total coverage\n');
                    charm_1.display('reset');
                    this.createCoverageReport(this.reportType, map);
                }
                var numPassedTests = numTests - numFailedTests - numSkippedTests;
                var message = "TOTAL: tested " + numEnvironments + " platforms, " + numPassedTests + " passed, " + numFailedTests + " failed";
                if (numSkippedTests) {
                    message += ", " + numSkippedTests + " skipped";
                }
                if (this.hasRunErrors) {
                    message += '; fatal error occurred';
                }
                else if (this.hasSuiteErrors) {
                    message += '; suite error occurred';
                }
                charm_1.display('bright');
                charm_1.foreground(numFailedTests > 0 || this.hasRunErrors || this.hasSuiteErrors ? 'red' : 'green');
                charm_1.write(message);
                charm_1.display('reset');
                charm_1.write('\n');
            }
        };
        Runner.prototype.serverStart = function (server) {
            var message = "Listening on localhost:" + server.port;
            if (server.socketPort) {
                message += " (ws " + server.socketPort + ")";
            }
            this.charm.write(message + "\n");
        };
        Runner.prototype.suiteEnd = function (suite) {
            var session = this.sessions[suite.sessionId || ''];
            if (!session) {
                if (!this.serveOnly) {
                    var charm_2 = this.charm;
                    charm_2.display('bright');
                    charm_2.foreground('yellow');
                    charm_2.write('BUG: suiteEnd was received for invalid session ' + suite.sessionId);
                    charm_2.display('reset');
                    charm_2.write('\n');
                }
                return;
            }
            if (suite.error) {
                var error = suite.error;
                var charm_3 = this.charm;
                charm_3.foreground('red');
                charm_3.write('Suite ' + suite.id + ' FAILED\n');
                charm_3.write(this.formatError(error));
                charm_3.display('reset');
                charm_3.write('\n');
                session.hasSuiteErrors = true;
            }
            else if (!suite.hasParent) {
                if (session.coverage) {
                    this.charm.write('\n');
                    this.createCoverageReport(this.reportType, session.coverage);
                }
                else {
                    var charm_4 = this.charm;
                    charm_4.write('No unit test coverage for ' + suite.name);
                    charm_4.display('reset');
                    charm_4.write('\n');
                }
                var name_1 = suite.name;
                var hasError = suite.error || session.hasSuiteErrors;
                var numTests = suite.numTests;
                var numFailedTests = suite.numFailedTests;
                var numSkippedTests = suite.numSkippedTests;
                var numPassedTests = numTests - numFailedTests - numSkippedTests;
                var summary = name_1 + ": " + numPassedTests + " passed, " + numFailedTests + " failed";
                if (numSkippedTests) {
                    summary += ", " + numSkippedTests + " skipped";
                }
                if (hasError) {
                    summary += '; suite error occurred';
                }
                var charm_5 = this.charm;
                charm_5.display('bright');
                charm_5.foreground(numFailedTests || hasError > 0 ? 'red' : 'green');
                charm_5.write(summary);
                charm_5.display('reset');
                charm_5.write('\n');
            }
        };
        Runner.prototype.suiteStart = function (suite) {
            if (!suite.hasParent) {
                this.sessions[suite.sessionId || ''] = { suite: suite };
                if (suite.sessionId) {
                    this.charm.write('\n');
                    this.charm.write('‣ Created remote session ' + suite.name + ' (' + suite.sessionId + ')\n');
                }
            }
        };
        Runner.prototype.testEnd = function (test) {
            var charm = this.charm;
            if (test.error) {
                charm.foreground('red');
                charm.write('× ' + test.id);
                charm.write(' (' + (test.timeElapsed / 1000) + 's)');
                charm.write('\n');
                charm.write(util_1.prefix(this.formatError(test.error), '    '));
                charm.display('reset');
                charm.write('\n\n');
            }
            else if (test.skipped) {
                if (!this.hideSkipped) {
                    charm.write('~ ' + test.id);
                    charm.display('reset');
                    charm.write(' (' + (test.skipped || 'skipped') + ')');
                    charm.display('reset');
                    charm.write('\n');
                }
            }
            else {
                if (!this.hidePassed) {
                    charm.foreground('green');
                    charm.write('✓ ' + test.id);
                    charm.display('reset');
                    charm.write(' (' + (test.timeElapsed / 1000) + 's)');
                    charm.display('reset');
                    charm.write('\n');
                }
            }
        };
        Runner.prototype.tunnelDownloadProgress = function (message) {
            var progress = message.progress;
            this.charm.write('Tunnel download: ' + (progress.received / progress.total * 100).toFixed(3) + '%\r');
        };
        Runner.prototype.tunnelStart = function () {
            this.charm.write('Tunnel started\n');
        };
        Runner.prototype.tunnelStatus = function (message) {
            this.charm.write(message.status + '\x1b[K\r');
        };
        __decorate([
            eventHandler()
        ], Runner.prototype, "coverage", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "deprecated", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "error", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "warning", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "log", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "runEnd", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "serverStart", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "suiteEnd", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "suiteStart", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "testEnd", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "tunnelDownloadProgress", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "tunnelStart", null);
        __decorate([
            eventHandler()
        ], Runner.prototype, "tunnelStatus", null);
        return Runner;
    }(Coverage_1.default));
    exports.default = Runner;
});
//# sourceMappingURL=Runner.js.map