import Vue from 'vue'

export default {
    methods: {
        setEndpoint(endpoint) {
            this.endpoint = endpoint;
        },
        replaceUrlParameters(pattern, replaceData) {
            var re = /\{([^\}]+)?\}/g, match;

            while (match = re.exec(pattern)) {
                pattern = pattern.replace(match[0], replaceData[match[1]])
                re.lastIndex = 0;
            }

            return pattern;
        },
        setQueryParameters(url, parameters) {
            let fakeHost = 'https://fakehost.local';
            url = new URL(fakeHost + url);
            Object.keys(parameters).forEach((key) => {
                url.searchParams.set(key, parameters[key]);
            });

            return url.toString().replace(fakeHost, '');
        },
        _fetch(url, options) {
            options = extend({
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                },
            }, options);

            var f = fetch(url, options);
            if (options.headers.Accept === 'application/json') {
                f = f.then(function (response) {
                    return response.json();
                });
            }

            f.catch((err) => {
                console.log(err);
            })

            return f;
        },
        post(url, data) {
            var opts = {method: 'POST', headers: {'Accept': 'application/json',},};
            // console.log('post data');
            // console.log(data);
            if (data instanceof FormData) {
                // console.log('DATA SEEM TO BE FORMDATA, POSTING');
                opts.body = data;
            } else {
                // console.log('DATA IS NOT FORMDATA => CONVERTING');
                var formData = new FormData();
                Object.keys(data).forEach(function (key) {
                    formData.append(key, data[key]);
                });
                opts.body = formData;
                // console.log('formData');
                // console.log(formData);
            }

            // console.log(opts.body);
            return this._fetch(this.endpoint + url, opts);
        },
        get(url) {
            var opts = {method: 'GET', headers: {'Accept': 'application/json',},};

            return this._fetch(this.endpoint + url, opts);
        },
        delete(url) {
            var opts = {method: 'DELETE', headers: {'Accept': 'application/json',},};

            return this._fetch(this.endpoint + url, opts);
        },
    }
}