import axios from 'axios';

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function getCommonHeaders(params = {}) {
    var accessToken, headers = {};
    if(!params.token) {
        accessToken = getCookie('access_token');
        // accessToken = "a22eea52-6d4b-47a8-b22b-e9b654ad04f7";
    } else {
        accessToken = params.token;
    }
    headers = {
        'Authorization': 'Bearer ' + accessToken,
        'Source': 'PRIME_PANEL'
    };
    if(params.user && params.user.defaultLocation) {
        headers.Locations = params.user.defaultLocation;
    }
    if(params.user && params.user.all_locations_selected) {
        headers.all_locations_selected = true;
    }
    if(params.user && params.user.userId) {
        headers.user = params.user.userId;
    }
    return headers;
}

function doHttpGet(url, options) {
    options = options || {};
    options.headers = Object.assign(options.headers || {}, getCommonHeaders(options));
    return axios.get(url, options);
}

function doHttpPost(url, content, options) {
    options = options || {};
    options.headers = Object.assign(options.headers || {}, getCommonHeaders(options));
    return axios.post(url, content, options);
}

function doHttpPatch(url, content, options) {
    options = options || {};
    options.headers = Object.assign(options.headers || {}, getCommonHeaders(options));
    return axios.patch(url, content, options);
}

function doHttpPut(url, content, options) {
    options = options || {};
    options.headers = Object.assign(options.headers || {}, getCommonHeaders(options));
    return axios.put(url, content, options);
}

function doHttpDelete(url, options) {
    options = options || {};
    options.headers = Object.assign(options.headers || {}, getCommonHeaders(options));
    return axios.delete(url, options);
}

function abortRequest(requestId){
    axios.abort(requestId);
}

function handleGenericResponse(response){
    if(response.data.status == 'SUCCESS'){
        return {'type':'success','data':response.data.response}
    }
    else if(response.data.status == 'ERROR'||response.data.status == 'FAILURE'){
        return handleError(response);
    }
}

function handleError(error){
    if(error.status=='FAILURE'||error.status=='ERROR'||error.data.status=='FAILURE'||error.data.status=='ERROR'){
        return {'type':'failure','data':(error.errorMessage||error.data.errorMessage)}
    }
    else{
        return {'type':'failure','data':'Unhandled Error , Kindly report this to tech team'}
    }
}

export { doHttpGet, doHttpPost, doHttpPatch, doHttpDelete, doHttpPut, getCookie, handleGenericResponse, handleError, abortRequest };
