import axios from 'axios';

const baseURL = "http://localhost:8000/api";

let csrfToken = "";
let userToken = "";

const api = axios.create({
    baseURL: baseURL,
    headers: {
        'Content-Type': 'application/json'
    }
});

api.interceptors.request.use(async config => {
    const { method } = config;
    if (method === 'post' || method === 'put' || method === 'delete' || method === 'options'
    ) {
        // csrfToken = await getCSRFToken(config.url);
        // config.headers['X-CSRFToken'] = csrfToken;
        if(userToken !== ""){
            config.headers.Authorization = 'Token ' + userToken;
        }else{
            userToken = sessionStorage.getItem('userToken')
            config.headers.Authorization = 'Token ' + userToken;
        }
    }
    if (method === 'get'){
        if(userToken !== ""){
            config.headers.Authorization = 'Token ' + userToken;
        }else{
            userToken = sessionStorage.getItem('userToken')
            config.headers.Authorization = 'Token ' + userToken;
        }
    }
    return config;
});
 
async function getCSRFToken(url) {
    console.log(csrfToken, baseURL + url)
    if(csrfToken === ""){
        const response = await axios.get(baseURL + url);
        csrfToken = response.data.csrftoken; 
        return csrfToken;
    }else{
        return csrfToken;
    }
}

export function setUserToken(token) {
    userToken = token;
    sessionStorage.setItem('userToken', token)
    console.log("TOKEN is " + token);
}

export async function getData(url = '', params = {}){
    api.defaults.headers["Content-Type"] = 'application/json';
    api.headers = {
        'Content-Type': 'application/json'
    }

    const response = await api.get(url, {params: params});
    return response.data;
}

export async function postData(url = '', data = {}) {
    api.defaults.headers["Content-Type"] = 'application/json';
    api.headers = {
        'Content-Type': 'application/json'
    }
    const response = await api.post(url, data);
    return response.data;
}

export async function deleteData(url = '', data = {}) {
    api.defaults.headers["Content-Type"] = 'application/json';
    api.headers = {
        'Content-Type': 'application/json'
    }
    const response = await api.delete(url, {data: data});
    return response.data;
}
export async function postFile(url = '', data ={}) {
    api.defaults.headers["Content-Type"] = "multipart/form-data";
    const response = await api.post(url, data);
    return response.data;
}