// модуль для работы с REST API сервера

// адрес сервера
const serverUrl = "http://localhost:8081";

export function getRealDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = `0${date.getMonth() + 1}`.slice(-2);
    const day = `0${date.getDate()}`.slice(-2);

    return `${year}-${month}-${day}`;
}
// функция возвращает объект нужной структуры для отправки на сервер
function createLineObject(itemName, itemDescription, itemImage) {
    return {
        date: getRealDate(),
        name: itemName,
        description: itemDescription,
        image: itemImage,
    };
}

// обращение к серверу для получения всех записей (get)
export async function getAllLines() {
    const response = await fetch(`${serverUrl}/lines`);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}

// обращение к серверу для создания записи (post)
// объект отправляется в теле запроса (body)
export async function createLine(itemName, description, image) {
    const itemObject = createLineObject(itemName, description, image);

    const options = {
        method: "POST",
        body: JSON.stringify(itemObject),
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
        },
    };

    const response = await fetch(`${serverUrl}/lines`, options);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}

// обращение к серверу для обновления записи по id (put)
// объект отправляется в теле  запроса (body)
// id передается в качестве части пути URL get-запроса
export async function updateLine(id, itemName, description, image) {
    const itemObject = createLineObject(itemName, description, image);

    const options = {
        method: "PUT",
        body: JSON.stringify(itemObject),
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
        },
    };

    const response = await fetch(`${serverUrl}/lines/${id}`, options);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}

// обращение к серверу для удаления записи по id (delete)
// id передается в качестве части пути URL get-запроса
export async function deleteLine(id) {
    const options = {
        method: "DELETE",
    };

    const response = await fetch(`${serverUrl}/lines/${id}`, options);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}