const API_URL = "/api/entry";
const API_TODOLIST_URL = "/api/todolist";

export function getEntriesByTodoListId(todoListId,token){
    return fetch(`${API_TODOLIST_URL}/${todoListId}/entries`, {
		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 getEntryById(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 updateEntry(id,title,token){
    return fetch(`${API_URL}/${id}?title=${title}`, {
		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 addEntryToTodo(todoListId,title,done,token){
    return fetch(`${API_TODOLIST_URL}/${todoListId}/entries`, {
		method: "POST",
        headers: {
			Accept: "application/json",
            Authorization : "Bearer  " + token,
            "Content-Type": "application/json"
		},
        body: JSON.stringify({
			title: title,
            done: done
		})
	}).then(r =>{
        if(r.status >= 200 && r.status < 300){
            return r.json();
        }
        else {
            throw new Error(r.status);
        }
    });
}

export function deleteEntry(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);
        }
    });
}