function combineUrl(url) {
    if (/^(https?|wss?|ftp):/.test(url)) {
        return url;
    }
    if (typeof consts === 'undefined') {
        return url;
    }
    return (consts.path || '') + url;
}

function get(url, options = {}) {
    return fetch(combineUrl(url), {
        method: options.method || 'GET',
        headers: {
            ...options.customerHeaders,
            'Accept': options.accept || 'application/json'
        },
        signal: options.signal,
        cache: 'default'
    });
}

function post(url, data, options = {}) {
    // let contentType;
    if (data instanceof FormData) {
        // contentType = 'multipart/form-data';
    } else {
        if (typeof data !== 'string') {
            data = JSON.stringify(data);
        }
        // contentType = 'application/json';
        if (options.customerHeaders == null) {
            options.customerHeaders = {};
        }
        if (options.customerHeaders['Content-Type'] == null) {
            options.customerHeaders['Content-Type'] = 'application/json';
        }
    }
    return fetch(combineUrl(url), {
        method: options.method || 'POST',
        headers: options.customerHeaders,
        body: data,
        signal: options.signal,
        cache: 'no-cache'
    });
}

function upload(url, data, options = {}) {
    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (this.readyState === XMLHttpRequest.DONE) {
                if (this.status === 200) {
                    resolve(this);
                } else {
                    reject(`${this.status} ${this.statusText}: ${this.responseText}`);
                }
            }
        };
        if (typeof options.progress === 'function') {
            request.upload.addEventListener('progress', function (ev) {
                if (ev.lengthComputable) {
                    options.progress.call(this, ev);
                }
            }, false);
        }
        request.open('POST', combineUrl(url));
        if (options.customerHeaders != null) {
            for (let header of Object.entries(options.customerHeaders)) {
                request.setRequestHeader(header[0], header[1]);
            }
        }
        request.send(data);
    });
}

export {
    get,
    post,
    upload
}