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

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

export 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.customHeaders == null) {
            options.customHeaders = {};
        }
        if (options.customHeaders['Content-Type'] == null) {
            options.customHeaders['Content-Type'] = 'application/json';
        }
    }
    const opts = {
        method: options.method || 'POST',
        headers: options.customHeaders,
        body: data,
        signal: options.signal,
        cache: 'no-cache'
    };
    if (options.diagnostic) {
        const started = new Date().getTime();
        return new Promise((resolve, reject) => {
            fetch(combineUrl(url), opts).then(response => {
                resolve({
                    time: new Date().getTime() - started,
                    response
                });
            }).catch(reject);
        });
    }
    return fetch(combineUrl(url), opts);
}

export 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.customHeaders != null) {
            for (let header of Object.entries(options.customHeaders)) {
                request.setRequestHeader(header[0], header[1]);
            }
        }
        request.send(data);
    });
}