export default {
    actions: {
        crudRequest({getters, dispatch},  {endpoint, method, parameters}){
            // console.log(endpoint);
            // console.log(window.LARAVEL_VAPOR_ENABLED);
            return dispatch('ensureReCaptchaIsSet').then(function () {
                let combinedAbsoluteUrl = endpoint;
                if(window.LARAVEL_VAPOR_ENABLED){
                    endpoint = encodeSpecificPartOfUrl(endpoint);
                    let queryDomain = endpoint.split('?')[0];
                    let encodedParams = endpoint.split('?')[1];
                    let decodedParams = fullyDecodeURI(encodedParams);
                    const queryParams = encodeURIComponent(decodedParams);
                    queryDomain = encodeUrlWithoutQueryParameter(queryDomain)

                    encodedParams = queryParams.toString();
                    let filteredEncodedParams = encodedParams.replace(/%3D/g,'=');
                    filteredEncodedParams = filteredEncodedParams.replace(/%26/g,'&');
                    combinedAbsoluteUrl = queryDomain;
                    if(filteredEncodedParams !== undefined && filteredEncodedParams !== 'undefined'){
                        combinedAbsoluteUrl = queryDomain + '?' + filteredEncodedParams;
                    }
                }
                // return fetch(endpoint, {
                return fetch(combinedAbsoluteUrl, {
                    method: method,
                    responseType: 'json',
                    body: parameters ? JSON.stringify(parameters):null,
                    headers: {
                        'content-type': 'application/json',
                        'Authorization': 'Bearer '+getters.getAccessToken,
                        'captcha-token': getters.getReCaptcha
                    }
                }).then(response => {

                    if(response.status === 401 && window.location.href !== route('login')){
                        dispatch('userAuthentication', {access_token: '', redirect_url: '/'});
                    }

                    return response;

                })
            });
        }
    }
}

function isEncoded(uri) {
    uri = uri || '';
    return uri !== decodeURIComponent(uri);
}

function fullyDecodeURI(uri){
    while (isEncoded(uri)){
        uri = decodeURIComponent(uri);
    }
    return uri;
}

function encodeUrlWithoutQueryParameter(url){
    let regex = /\[\d+\]/;
    let match = url.match(regex);

    if (match) {
        let encodedPattern = encodeURIComponent(match[0]);
        let encodedUrl = url.replace(match[0], encodedPattern);
        return encodedUrl;
    }

    return url;
}

function encodeSpecificPartOfUrl(url) {
    let encodedUrl = url.replace('[','%5B');
    encodedUrl = encodedUrl.replace(']','%5D');
    encodedUrl = encodedUrl.replace(',','%2C');
    return encodedUrl;
}
