const API_URL = "/api/todolist"

export function getTodos(token){
    return fetch(`${API_URL}`, {
		method: "GET",
		headers: {
			Accept: "application/json",
            Authorization : "Bearer  " + token,
		}
	}).then(r =>{
        if(r.status >= 200 && r.status < 300){
            return r.json();
        }
        else {
            throw new Error(r.status);
        }
    });
}

export function getTodoById(id,token){
    return fetch(`${API_URL}/${id}`, {
		method: "GET",
		headers: {
			Accept: "application/json",
            Authorization : "Bearer  " + token,
		}
	}).then(r =>{
        if(r.status >= 200 && r.status < 300){
            return r.json();
        }
        else {
            throw new Error(r.status);
        }
    });
}

export function updateTodo(id,name,token){
    return fetch(`${API_URL}/${id}?name=${name}`, {
		method: "PUT",
        headers: {
			Accept: "application/json",
            Authorization : "Bearer  " + token,
		},
	}).then(r =>{
        if(r.status >= 200 && r.status < 300){
            return r.json();
        }
        else {
            throw new Error(r.status);
        }
    });
}

export function addTodo(name,token){
    return fetch(`${API_URL}`, {
		method: "POST",
        headers: {
			Accept: "application/json",
            Authorization : "Bearer  " + token,
            "Content-Type": "application/json"
		},
        body: JSON.stringify({
			name: name
		})
	}).then(r =>{
        if(r.status >= 200 && r.status < 300){
            return r.json();
        }
        else {
            throw new Error(r.status);
        }
    });
}

export function deleteTodo(id,token){
    return fetch(`${API_URL}/${id}`, {
		method: "DELETE",
        headers: {
            Authorization : "Bearer  " + token,
		},
	}).then(r =>{
        if(r.status >= 200 && r.status < 300){
            return r.status;
        }
        else {
            throw new Error(r.status);
        }
    });
}