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", "../Suite", "./Reporter", "fs", "path"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Suite_1 = require("../Suite");
    var Reporter_1 = require("./Reporter");
    var fs_1 = require("fs");
    var path_1 = require("path");
    /**
     * There is no formal spec for this format and everyone does it differently, so good luck! We've mashed as many of the
     * different incompatible JUnit/xUnit XSDs as possible into one reporter.
     */
    var JUnit = (function (_super) {
        __extends(JUnit, _super);
        function JUnit(executor, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this, executor, options) || this;
            if (options.filename) {
                _this.filename = options.filename;
                if (path_1.dirname(_this.filename) !== '.') {
                    fs_1.mkdir(path_1.dirname(_this.filename));
                }
                _this.output = fs_1.createWriteStream(_this.filename);
            }
            return _this;
        }
        JUnit.prototype.runEnd = function () {
            var _this = this;
            var rootNode = new XmlNode('testsuites');
            this.executor.suites.forEach(function (suite) {
                rootNode.childNodes.push(createSuiteNode(suite, _this));
            });
            var report = '<?xml version="1.0" encoding="UTF-8" ?>' + rootNode.toString() + '\n';
            this.output.end(report);
        };
        __decorate([
            Reporter_1.eventHandler()
        ], JUnit.prototype, "runEnd", null);
        return JUnit;
    }(Reporter_1.default));
    exports.default = JUnit;
    /**
     * Simple XML generator.
     * @constructor
     * @param {string} nodeName The node name.
     * @param {Object?} attributes Optional attributes.
     */
    var XmlNode = (function () {
        function XmlNode(nodeName, attributes) {
            this.nodeName = '';
            this.childNodes = [];
            this.nodeName = nodeName;
            if (attributes && attributes.childNodes) {
                this.childNodes = attributes.childNodes;
                attributes.childNodes = undefined;
            }
            this.attributes = attributes || {};
        }
        /**
         * Creates a new XML node and pushes it to the end of the current node.
         * @param {string} nodeName The node name for the new node.
         * @param {Object?} attributes Optional attributes for the new node.
         * @param {(XmlNode|string)[]?} childNodes Optional child nodes for the new node.
         * @returns {XmlNode} A new node.
         */
        XmlNode.prototype.createNode = function (nodeName, attributes) {
            var node = new XmlNode(nodeName, attributes);
            this.childNodes.push(node);
            return node;
        };
        XmlNode.prototype._escape = function (str) {
            return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
        };
        XmlNode.prototype._serializeAttributes = function () {
            var attributes = this.attributes;
            var nodes = [];
            for (var key in attributes) {
                if (attributes[key] != null) {
                    nodes.push(key + '="' + this._escape(attributes[key]) + '"');
                }
            }
            return nodes.length ? ' ' + nodes.join(' ') : '';
        };
        XmlNode.prototype._serializeContent = function () {
            var nodeList = this.childNodes;
            var nodes = [];
            for (var i = 0, j = nodeList.length; i < j; ++i) {
                nodes.push(typeof nodeList[i] === 'string' ? this._escape(nodeList[i]) : nodeList[i].toString());
            }
            return nodes.join('');
        };
        /**
         * Outputs the node as a serialised XML string.
         * @returns {string}
         */
        XmlNode.prototype.toString = function () {
            var children = this._serializeContent();
            return '<' + this.nodeName + this._serializeAttributes() +
                (children.length ? '>' + children + '</' + this.nodeName + '>' : '/>');
        };
        return XmlNode;
    }());
    function createSuiteNode(suite, reporter) {
        return new XmlNode('testsuite', {
            name: suite.name || 'Node.js',
            failures: suite.numFailedTests,
            skipped: suite.numSkippedTests,
            tests: suite.numTests,
            time: suite.timeElapsed / 1000,
            childNodes: suite.tests.map(function (test) { return createTestNode(test, reporter); })
        });
    }
    function createTestNode(test, reporter) {
        if (test instanceof Suite_1.default) {
            return createSuiteNode(test, reporter);
        }
        var node = new XmlNode('testcase', {
            name: test.name,
            time: test.timeElapsed / 1000,
            status: test.error ? 1 : 0
        });
        if (test.error) {
            node.createNode(test.error.name === 'AssertionError' ? 'failure' : 'error', {
                childNodes: [reporter.formatError(test.error)],
                message: test.error.message,
                type: test.error.name
            });
        }
        else if (test.skipped != null) {
            node.createNode('skipped', {
                childNodes: [test.skipped]
            });
        }
        return node;
    }
});
//# sourceMappingURL=JUnit.js.map