function getError(option, xhr) {
    var msg = 'cannot post ' + option.action + ' ' + xhr.status + '\'';
    var err = new Error(msg);
    err.status = xhr.status;
    err.method = 'post';
    err.url = option.action;
    return err;
}

function getBody(xhr) {
    var text = xhr.responseText || xhr.response;
    if (!text) {
        return text;
    }

    try {
        return JSON.parse(text);
    } catch (e) {
        return text;
    }
}

export default function upload(option) {
    var xhr = new window.XMLHttpRequest();
    var data = option.data;
    if (option.onProgress && xhr.upload) {
        xhr.upload.onprogress = function (e) {
            if (e.total > 0) {
                e.progress = parseInt(e.loaded / e.total * 100);
            }
            option.onProgress(e);
        };
    }

    xhr.onreadystatechange = function () {
        // console.log(`onreadystatechange: xhr.readyState == ${xhr.readyState}, xhr.status == ${xhr.status}`);
    };

    xhr.onloadstart = function () {};

    xhr.onerror = function error(e) {
        option.onError(e);
    };

    xhr.onload = function () {
        if (xhr.status < 200 || xhr.status >= 300) {
            return option.onError(getError(option, xhr), getBody(xhr));
        }

        option.onSuccess(getBody(xhr), xhr);
    };

    xhr.loadend = function () {};

    xhr.timeout = function () {};

    xhr.open(option.method || 'POST', option.action, true);

    var headers = option.headers || {};
    for (var h in headers) {
        if (headers.hasOwnProperty(h) && headers[h] !== null) {
            xhr.setRequestHeader(h, headers[h]);
        }
    }
    xhr.send(data);

    return {
        abort: function abort() {
            xhr.abort();
        }
    };
}