"use strict";
const os_1 = require("os");
const constants = require("./constants");
class XmlValidator {
    constructor($fs, $logger) {
        this.$fs = $fs;
        this.$logger = $logger;
    }
    validateXmlFiles(sourceFiles) {
        return (() => {
            let xmlHasErrors = false;
            sourceFiles
                .filter(file => _.endsWith(file, constants.XML_FILE_EXTENSION))
                .forEach(file => {
                let errorOutput = this.getXmlFileErrors(file).wait();
                let hasErrors = !!errorOutput;
                xmlHasErrors = xmlHasErrors || hasErrors;
                if (hasErrors) {
                    this.$logger.info(`${file} has syntax errors.`.red.bold);
                    this.$logger.out(errorOutput.yellow);
                }
            });
            return !xmlHasErrors;
        }).future()();
    }
    getXmlFileErrors(sourceFile) {
        return (() => {
            let errorOutput = "";
            let fileContents = this.$fs.readText(sourceFile).wait();
            let domErrorHandler = (level, msg) => {
                errorOutput += level + os_1.EOL + msg + os_1.EOL;
            };
            this.getDomParser(domErrorHandler).parseFromString(fileContents, "text/xml");
            return errorOutput || null;
        }).future()();
    }
    getDomParser(errorHandler) {
        let DomParser = require("xmldom").DOMParser;
        let parser = new DomParser({
            locator: {},
            errorHandler: errorHandler
        });
        return parser;
    }
}
exports.XmlValidator = XmlValidator;
$injector.register("xmlValidator", XmlValidator);
