export default {
    actions: {
        crudRequestV2({getters, dispatch},  {endpoint, method, parameters}){
            const queryDomain = endpoint.split('?')[0];
            let encodedParams = endpoint.split('?')[1];
            let decodedParams = fullyDecodeURI(encodedParams);
            const queryParams = encodeURIComponent(decodedParams);
            encodedParams = queryParams.toString();
            let filteredEncodedParams = encodedParams.replace(/%3D/g,'=');
            filteredEncodedParams = filteredEncodedParams.replace(/%26/g,'&');
            let 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
                }
            }).then(response => {
                if(response.status === 401 && window.location.href !== route('login') && window.location.href.indexOf(route('last_mile_delivery.login')) <= -1){
                    dispatch('userAuthentication', {access_token: '', redirect_url: [7, 8].includes(getters.getCompanyModuleType) ? route('last_mile_delivery.login') : route('login')});
                }

                return response;

            })
        }
    }
}

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

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