"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var xhr_1 = require("@dojo/core/request/providers/xhr");
var lang_1 = require("@dojo/core/lang");
var util_1 = require("../common/util");
function getConfig() {
    var args = util_1.parseArgs(parseQuery());
    if (args.config) {
        var path = resolvePath(args.config, args.basePath);
        return loadConfig(path).then(function (config) { return lang_1.deepMixin(config, args); });
    }
    else {
        var path = resolvePath('intern.json', args.basePath);
        return loadConfig(path).then(function (config) { return lang_1.deepMixin(config, args); }, function (_error) { return args; });
    }
}
exports.getConfig = getConfig;
function loadJson(path, basePath) {
    if (path[0] !== '/') {
        basePath = basePath == null ? '/' : basePath;
        path = "" + basePath + path;
    }
    return xhr_1.default(path).then(function (response) {
        return response.text().then(function (text) {
            return util_1.parseJSON(text);
        });
    });
}
exports.loadJson = loadJson;
function normalizePath(path) {
    var parts = path.replace(/\\/g, '/').split('/');
    var result = [];
    for (var i = 0; i < parts.length; ++i) {
        var part = parts[i];
        if (!part || part === '.') {
            if (i === 0 || i === parts.length - 1) {
                result.push('');
            }
            continue;
        }
        if (part === '..') {
            if (result.length && result[result.length - 1] !== '..') {
                result.pop();
            }
            else {
                result.push(part);
            }
        }
        else {
            result.push(part);
        }
    }
    return result.join('/');
}
exports.normalizePath = normalizePath;
function parseQuery(query) {
    query = query || location.search.slice(1);
    return query.split('&').filter(function (arg) {
        return arg !== '' && arg[0] !== '=';
    }).map(function (arg) {
        var parts = arg.split('=');
        var name = decodeURIComponent(parts[0]);
        if (parts[1]) {
            return name + "=" + decodeURIComponent(parts[1]);
        }
        return name;
    });
}
exports.parseQuery = parseQuery;
function loadConfig(configPath) {
    return loadJson(configPath).then(function (config) {
        if (config.extends) {
            var parts = configPath.split('/');
            var extensionPath = parts.slice(0, parts.length - 1).concat(config.extends).join('/');
            return loadConfig(extensionPath).then(function (extension) {
                return lang_1.deepMixin(extension, config);
            });
        }
        else {
            return config;
        }
    });
}
function resolvePath(path, basePath) {
    if (path[0] !== '/') {
        basePath = basePath == null ? '/' : basePath;
        path = "" + basePath + path;
    }
    return path;
}
//# sourceMappingURL=util.js.map