"use strict";
var Promise = require('any-promise');
var response_1 = require('./response');
var index_1 = require('./plugins/index');
function createTransport(options) {
    return {
        use: use,
        abort: abort,
        open: function (request) {
            return handle(request, options);
        }
    };
}
exports.createTransport = createTransport;
var use = [index_1.stringify(), index_1.headers()];
function handle(request, options) {
    return new Promise(function (resolve, reject) {
        var type = options.type || 'text';
        var url = request.url, method = request.method;
        if (window.location.protocol === 'https:' && /^http\:/.test(url)) {
            return reject(request.error("The request to \"" + url + "\" was blocked", 'EBLOCKED'));
        }
        var xhr = request._raw = new XMLHttpRequest();
        function done() {
            return new Promise(function (resolve) {
                return resolve(new response_1.default({
                    status: xhr.status === 1223 ? 204 : xhr.status,
                    statusText: xhr.statusText,
                    rawHeaders: parseToRawHeaders(xhr.getAllResponseHeaders()),
                    body: type === 'text' ? xhr.responseText : xhr.response,
                    url: xhr.responseURL
                }));
            });
        }
        xhr.onload = function () { return resolve(done()); };
        xhr.onabort = function () { return resolve(done()); };
        xhr.onerror = function () {
            return reject(request.error("Unable to connect to \"" + request.url + "\"", 'EUNAVAILABLE'));
        };
        xhr.onprogress = function (e) {
            if (e.lengthComputable) {
                request.downloadLength = e.total;
            }
            request._setDownloadedBytes(e.loaded);
        };
        xhr.upload.onloadend = function () { return request.downloaded = 1; };
        if (method === 'GET' || method === 'HEAD' || !xhr.upload) {
            request.uploadLength = 0;
            request._setUploadedBytes(0, 1);
        }
        else {
            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    request.uploadLength = e.total;
                }
                request._setUploadedBytes(e.loaded);
            };
            xhr.upload.onloadend = function () { return request.uploaded = 1; };
        }
        try {
            xhr.open(method, url);
        }
        catch (e) {
            return reject(request.error("Refused to connect to \"" + url + "\"", 'ECSP', e));
        }
        if (options.withCredentials) {
            xhr.withCredentials = true;
        }
        if (options.overrideMimeType) {
            xhr.overrideMimeType(options.overrideMimeType);
        }
        if (type !== 'text') {
            try {
                xhr.responseType = type;
            }
            finally {
                if (xhr.responseType !== type) {
                    return reject(request.error("Unsupported type: " + type, 'ETYPE'));
                }
            }
        }
        for (var i = 0; i < request.rawHeaders.length; i += 2) {
            xhr.setRequestHeader(request.rawHeaders[i], request.rawHeaders[i + 1]);
        }
        xhr.send(request.body);
    });
}
function abort(request) {
    request._raw.abort();
}
function parseToRawHeaders(headers) {
    var rawHeaders = [];
    var lines = headers.split(/\r?\n/);
    for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
        var line = lines_1[_i];
        if (line) {
            var indexOf = line.indexOf(':');
            var name_1 = line.substr(0, indexOf).trim();
            var value = line.substr(indexOf + 1).trim();
            rawHeaders.push(name_1, value);
        }
    }
    return rawHeaders;
}
//# sourceMappingURL=browser.js.map