From ddbc657b14f5fd688a17463beb73bfc46b89c0c6 Mon Sep 17 00:00:00 2001 From: ReBy298 Date: Mon, 2 Dec 2024 03:57:01 -0600 Subject: [PATCH] Refactored code based on Copilot suggestions --- src/App.js | 312 +----------------- src/components/Footer/Footer.jsx | 58 ++-- src/components/Header/Header.jsx | 126 +++---- src/components/Modal/Modal_PopUp.jsx | 20 +- .../Pagination/Tasks_Pagination.jsx | 7 +- src/components/TaskList/Tasks_List.jsx | 19 +- src/hooks/useTodo.js | 292 ++++++++++++++++ 7 files changed, 423 insertions(+), 411 deletions(-) create mode 100644 src/hooks/useTodo.js diff --git a/src/App.js b/src/App.js index 13c8cfa..5e0f8db 100644 --- a/src/App.js +++ b/src/App.js @@ -5,7 +5,6 @@ import { Tasks_List } from "./components/TaskList/Tasks_List"; import {Modal_PopUp} from "./components/Modal/Modal_PopUp"; import { Tasks_Pagination } from "./components/Pagination/Tasks_Pagination"; import { Footer } from "./components/Footer/Footer"; -import React, { useEffect, useState } from "react"; import { Container, Paper, @@ -17,315 +16,12 @@ import "../node_modules/@syncfusion/ej2-lists/styles/material.css"; import "../node_modules/@syncfusion/ej2-inputs/styles/material.css"; import "../node_modules/@syncfusion/ej2-popups/styles/material.css"; import "../node_modules/@syncfusion/ej2-react-calendars/styles/material.css"; - +import { useTodo } from './hooks/useTodo'; function App() { - const [todoItems, setTodoItems] = useState(null); - const [page, setPage] = useState(1); - const [totalPages, setTotalPages] = useState(1); - const [name, setName] = useState(""); - const [priority, setPriority] = useState("All"); - const [state, setState] = useState("All"); - const [label, setLabel] = useState(true); - const [open, setOpen] = useState(false); - const [dueDate, setDueDate] = useState(""); - const [taskName, setTaskName] = useState(""); - const [priority_Modal, setPriorityModal] = useState(""); - const [taskToEdit, setTaskToEdit] = useState(null); - const [sortBy1, setSortBy1] = useState("dueDate"); - const [order1, setOrder1] = useState("asc"); - const [sortBy2, setSortBy2] = useState("priority"); - const [order2, setOrder2] = useState("asc"); - const [averageTimeAll, setAverageTimeAll] = useState(""); - const [averageTimeHigh, setAverageTimeHigh] = useState(""); - const [averageTimeMedium, setAverageTimeMedium] = useState(""); - const [averageTimeLow, SetAverageTimeLow] = useState(""); - const [fetchFlags, setFetchFlags] = useState(true); - const [todoItemsFlags, setTodoItemsFlags] = useState([]); - - - useEffect(() => { - if (fetchFlags) { - fetchTodoItemsFlags(); - setFetchFlags(false); - } - - fetchTodoItems(); - fetchAverageTimes(); - if (taskToEdit) { - setTaskName(taskToEdit.name); - setPriorityModal(taskToEdit.priority); - setDueDate(taskToEdit.dueDate); - } else { - setTaskName('Nueva Tarea'); - setPriorityModal('Medium'); - setDueDate(''); - } - }, [page, taskToEdit, sortBy1, sortBy2, order1, order2, fetchFlags]); - - - - const fetchTodoItemsFlags = () => { - fetch(`http://localhost:9090/api/todos/colorFlags`) - .then((response) => response.json()) - .then((data) => { - console.log("Todo Items List Flags:", data); - setTodoItemsFlags(data); - }) - .catch((error) => { - console.error('Error fetching todo items:', error); - }); - }; - - const fetchTodoItems = () => { - fetch(`http://localhost:9090/api/todos?name=${name}&priority=${priority}&state=${state}&page=${page}&pageSize=10&sortBy1=${sortBy1}&order1=${order1}&sortBy2=${sortBy2}&order2=${order2}`) - .then((response) => response.json()) - .then((data) => { - console.log("Todo Items List:", data); - setTodoItems(data.items); - setTotalPages(data.totalPages); - }) - .catch((error) => { - console.error('Error fetching todo items:', error); - }); - }; - - - - const fetchAverageTimes = () => { - fetch('http://localhost:9090/api/todos/averageTime') - .then(response => response.json()) - .then(data => { - setAverageTimeAll(data.averageTimeAll); - setAverageTimeHigh(data.averageTimeHigh); - setAverageTimeMedium(data.averageTimeMedium); - SetAverageTimeLow(data.averageTimeLow); - }) - .catch((error) => { - console.error('Error fetching average times:', error); - }); - }; - - - - const handleSortClick = (field) => { - if (field === sortBy1) { - setOrder1(order1 === "asc" ? "desc" : "asc"); - } else { - setSortBy2(sortBy1); - setOrder2(order1); - setSortBy1(field); - setOrder1("asc"); - } - }; - - const handlePrioritySortClick = () => { - handleSortClick("priority"); - }; - - - const handleDueDateSortClick = () => { - handleSortClick("dueDate"); - }; - - - const handleSearch = () => { - fetchTodoItems(priority, name, state); - setPage(1); - }; - - const handleOpen = () => { - setOpen(true); - }; - - const handleClose = () => { - setOpen(false); - setTaskToEdit(null); // Resetea taskToEdit cuando cierras el modal - }; - - const handleToggleDone = (id) => { - // Crea una nueva copia de todoItems - const newTodoItems = [...todoItems]; - - // Encuentra la tarea en el nuevo array por su id - const task = newTodoItems.find((task) => task.id === id); - - if (task) { - // Cambia el valor de 'done' - task.done = !task.done; - - if (task.done === true) { - // Actualiza la tarea en el servidor - updateTaskDone(id, task) - .then(() => { - // Actualiza el estado con el nuevo array - setTodoItems(newTodoItems); - fetchAverageTimes(); - }) - .catch((error) => { - console.error('Error updating task:', error); - // Aquí puedes manejar los errores - }); - - } else { - // Actualiza la tarea en el servidor - updateTaskUndone(id, task) - .then(() => { - // Actualiza el estado con el nuevo array - setTodoItems(newTodoItems); - fetchAverageTimes(); - }) - .catch((error) => { - console.error('Error updating task:', error); - // Aquí puedes manejar los errores - }); - } - - } - } - - const handleSubmit = (event) => { - event.preventDefault(); - const task = { - name: taskName, - priority: priority_Modal, - dueDate: dueDate - }; - - if (taskToEdit && 'id' in taskToEdit) { - // Si taskToEdit no es null y tiene una propiedad 'id', actualiza la tarea - updateTask(taskToEdit.id, task) - .then(() => { - // Actualiza el estado de las tareas - setTodoItems(todoItems.map(item => item.id === taskToEdit.id ? { ...item, ...task } : item)); - setTaskToEdit(null); // Resetea taskToEdit después de actualizar la tarea - fetchTodoItems(); - fetchTodoItemsFlags(); - }) - .catch((error) => { - console.error('Error updating task:', error); - }); - setTodoItems(todoItems.map(task => task.id === taskToEdit.id ? updateTask : task)); - } else { - // Si taskToEdit es null, crea una nueva tarea - createTask(task) - .then(() => { - fetchTodoItems(); - fetchTodoItemsFlags(); - }) - .catch((error) => { - console.error('Error creating task: sera este el error', error); - }); - } - - handleClose(); - }; - - - const createTask = async (todoItem) => { - const response = await fetch(`http://localhost:9090/api/todos`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(todoItem), - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - const data = await response.json(); - console.log(data); - fetchTodoItems(); - // Aquí puedes actualizar tu estado o hacer algo con los datos devueltos - } - } - - - const updateTaskDone = async (id, todoItem) => { - - const response = await fetch(`http://localhost:9090/api/todos/${id}/done`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(todoItem), - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - const data = await response.json(); - console.log(data); - fetchTodoItems(); - fetchAverageTimes(); - // Aquí puedes actualizar tu estado o hacer algo con los datos devueltos - } - } - - const updateTaskUndone = async (id, todoItem) => { - const response = await fetch(`http://localhost:9090/api/todos/${id}/undone`, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(todoItem), - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - const data = await response.json(); - fetchTodoItems(); - fetchAverageTimes(); - console.log(data); - } - } - - const handleEditClick = (task) => { - setTaskToEdit(task); - setDueDate(task.dueDate); - handleOpen(); - }; - - - const updateTask = async (id, todoItem) => { - const response = await fetch(`http://localhost:9090/api/todos/${id}`, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(todoItem), - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - const data = await response.json(); - console.log(data); - fetchTodoItemsFlags(); - fetchTodoItems(); - } - } - const deleteTask = async (id) => { - const response = await fetch(`http://localhost:9090/api/todos/${id}`, { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } else { - setTodoItems(todoItems.filter(task => task.id !== id)); - console.log(`Task with id ${id} deleted.`); - fetchTodoItemsFlags(); - fetchTodoItems(); - fetchAverageTimes(); - } - } - + const { + todoItems, page, setPage, totalPages, name, setName, priority, setPriority, state, setState, label, setLabel, open, dueDate, setDueDate, taskName, setTaskName, priority_Modal, setPriorityModal, taskToEdit, averageTimeAll, averageTimeHigh, averageTimeMedium, averageTimeLow, todoItemsFlags, handleOpen, handleClose, handleToggleDone, handleSubmit, handleSearch, handlePrioritySortClick, handleDueDateSortClick, handleEditClick, deleteTask, + } = useTodo(); return ( diff --git a/src/components/Footer/Footer.jsx b/src/components/Footer/Footer.jsx index f3581d9..15e3770 100644 --- a/src/components/Footer/Footer.jsx +++ b/src/components/Footer/Footer.jsx @@ -5,36 +5,42 @@ import { Grid, } from '@mui/material'; - +// Footer component to display average task completion times export function Footer({ averageTimeAll, averageTimeHigh, averageTimeMedium, averageTimeLow}) { return ( + // Container to hold the footer content + {/* Grid container to layout the footer items with spacing and centered alignment */} - - - Average time to finish tasks: - - - {isNaN(averageTimeAll) ? "No done tasks" : (averageTimeAll / 60000).toFixed(2) + " min"} - - - - - Average time to finish tasks by priority: - - - {"High"}: {isNaN(averageTimeHigh) ? "No done tasks" : (averageTimeHigh / 60000).toFixed(2) + " min"} - - - {"Medium"}: {isNaN(averageTimeMedium) ? "No done tasks" : (averageTimeMedium / 60000).toFixed(2) + " min"} - - - {"Low"}: {isNaN(averageTimeLow) ? "No done tasks" : (averageTimeLow / 60000).toFixed(2) + " min"} - - + {/* Grid item to display the average time to finish all tasks */} + + + Average time to finish tasks: + + + {/* Display average time in minutes or a message if no tasks are done */} + {isNaN(averageTimeAll) ? "No done tasks" : (averageTimeAll / 60000).toFixed(2) + " min"} + + + {/* Grid item to display the average time to finish tasks by priority */} + + + Average time to finish tasks by priority: + + + {/* Display average time for high priority tasks in minutes or a message if no tasks are done */} + {"High"}: {isNaN(averageTimeHigh) ? "No done tasks" : (averageTimeHigh / 60000).toFixed(2) + " min"} + + + {/* Display average time for medium priority tasks in minutes or a message if no tasks are done */} + {"Medium"}: {isNaN(averageTimeMedium) ? "No done tasks" : (averageTimeMedium / 60000).toFixed(2) + " min"} + + + {/* Display average time for low priority tasks in minutes or a message if no tasks are done */} + {"Low"}: {isNaN(averageTimeLow) ? "No done tasks" : (averageTimeLow / 60000).toFixed(2) + " min"} + + ) -} - - +} \ No newline at end of file diff --git a/src/components/Header/Header.jsx b/src/components/Header/Header.jsx index 0c19e96..892096c 100644 --- a/src/components/Header/Header.jsx +++ b/src/components/Header/Header.jsx @@ -9,70 +9,78 @@ import { InputLabel, Grid, InputAdornment - } from '@mui/material'; +// Header component to handle task filtering and searching export function Header({name, setName, priority, setPriority, state, setState, label, setLabel, handleSearch, handleOpen}) { - return ( - - To-Do - + return ( + // Container to hold the header content + + {/* Title of the To-Do application */} + + To-Do + - - {label && Name} - { - setName(e.target.value); - setLabel(!e.target.value); - }} - InputProps={{ - startAdornment: !label && ( - Name - ), - }} - label= "Name" - /> - - - - - Priority - - - - - - State - - + {/* Form control for the task name input field */} + + {/* Conditionally render the input label if label prop is provided */} + {label && Name} + { + setName(e.target.value); + setLabel(!e.target.value); + }} + InputProps={{ + startAdornment: !label && ( + Name + ), + }} + label= "Name" + /> + + {/* Grid container to layout the filter options */} + + {/* Grid item for priority selection */} + + + Priority + + + + {/* Grid item for state selection */} + + + State + + + + {/* Grid item for search button */} + + + - - - - - - - - - - ) -} - + + ) +} \ No newline at end of file diff --git a/src/components/Modal/Modal_PopUp.jsx b/src/components/Modal/Modal_PopUp.jsx index 11189f4..5330d5c 100644 --- a/src/components/Modal/Modal_PopUp.jsx +++ b/src/components/Modal/Modal_PopUp.jsx @@ -8,20 +8,25 @@ import { FormControl, InputLabel, Modal - } from '@mui/material'; import { DateTimePickerComponent } from '@syncfusion/ej2-react-calendars'; +// Modal_PopUp component to handle adding and editing tasks export function Modal_PopUp({ open, handleClose, taskToEdit, handleSubmit, taskName, setTaskName, priority_Modal, setPriorityModal, dueDate, setDueDate }) { return ( + // Container to hold the modal content + {/* Modal component to display the popup */}
+ {/* Title of the modal, changes based on whether editing or adding a task */} {taskToEdit ? 'Edit To-Do' : 'New To-Do'} + {/* Form to handle task submission */}
+ {/* TextField for entering the task name */} + {/* FormControl for selecting task priority */} - Priority + Priority + {/* DateTimePickerComponent for selecting due date and time */} { - // Convierte la fecha y hora a tu zona horaria local + // Convert the date and time to local timezone let localDateTime = ""; if (e.value !== null) { localDateTime = new Date(e.value.getTime() - e.value.getTimezoneOffset() * 60000); @@ -51,16 +58,13 @@ export function Modal_PopUp({ open, handleClose, taskToEdit, handleSubmit, taskN }} min={new Date()} /> - + {/* Button to submit the form, changes text based on whether editing or adding a task */}
- -
) - } \ No newline at end of file diff --git a/src/components/Pagination/Tasks_Pagination.jsx b/src/components/Pagination/Tasks_Pagination.jsx index 59a18e9..f133958 100644 --- a/src/components/Pagination/Tasks_Pagination.jsx +++ b/src/components/Pagination/Tasks_Pagination.jsx @@ -1,4 +1,3 @@ - import { Container, Grid, @@ -6,7 +5,9 @@ import { PaginationItem, } from '@mui/material'; +// Tasks_Pagination component to handle pagination of tasks export function Tasks_Pagination({totalPages, page, setPage}) { + // Function to handle page change const handlePageChange = (event, value) => { if (value !== page) { setPage(value); @@ -14,13 +15,17 @@ export function Tasks_Pagination({totalPages, page, setPage}) { }; return ( + // Container to hold the pagination component + {/* Grid container to center the pagination */} + {/* Pagination component to navigate through pages */} ( + // Render each pagination item diff --git a/src/components/TaskList/Tasks_List.jsx b/src/components/TaskList/Tasks_List.jsx index 3ec7dcc..e924066 100644 --- a/src/components/TaskList/Tasks_List.jsx +++ b/src/components/TaskList/Tasks_List.jsx @@ -1,4 +1,3 @@ - import IconButton from '@mui/material/IconButton'; import { GrEdit } from "react-icons/gr"; import { FaSort } from "react-icons/fa"; @@ -13,10 +12,15 @@ import { TableHead, TableRow, } from '@mui/material'; + +// Tasks_List component to display and manage the list of tasks export function Tasks_List({ todoItems, handlePrioritySortClick, handleDueDateSortClick, todoItemsFlags, handleToggleDone, handleEditClick, deleteTask }) { return ( + // Container to hold the tasks list + {/* Check if there are todo items to display */} {todoItems && ( + // Table container to display the tasks in a table format @@ -34,11 +38,11 @@ export function Tasks_List({ todoItems, handlePrioritySortClick, handleDueDateSo {todoItems.map((task) => { - // Encuentra el objeto correspondiente en todoItemsFlags + // Find the corresponding flag object in todoItemsFlags const flagObject = todoItemsFlags.find(flagItem => flagItem.item.id === task.id); let flag = flagObject ? flagObject.flag : 0; - // Asigna un color de fondo en función del valor de la bandera + // Assign a background color based on the flag value let backgroundColor; switch (flag) { case 0: @@ -51,13 +55,14 @@ export function Tasks_List({ todoItems, handlePrioritySortClick, handleDueDateSo backgroundColor = '#FFFF99'; // 2 weeks between due date and today – Light yellow background color break; case 3: - backgroundColor = '#99FF99'; // More that 2 weeks between due date and today – Light green background color + backgroundColor = '#99FF99'; // More than 2 weeks between due date and today – Light green background color break; default: backgroundColor = 'transparent'; } return ( + // Table row for each task, with conditional styling based on task completion and flag ) -} - - - - +} \ No newline at end of file diff --git a/src/hooks/useTodo.js b/src/hooks/useTodo.js new file mode 100644 index 0000000..e1486ef --- /dev/null +++ b/src/hooks/useTodo.js @@ -0,0 +1,292 @@ +import { useState, useEffect } from 'react'; + +// Custom hook to manage todo items +export const useTodo = () => { + // State variables + const [todoItems, setTodoItems] = useState(null); + const [page, setPage] = useState(1); + const [totalPages, setTotalPages] = useState(1); + const [name, setName] = useState(""); + const [priority, setPriority] = useState("All"); + const [state, setState] = useState("All"); + const [label, setLabel] = useState(true); + const [open, setOpen] = useState(false); + const [dueDate, setDueDate] = useState(""); + const [taskName, setTaskName] = useState(""); + const [priority_Modal, setPriorityModal] = useState(""); + const [taskToEdit, setTaskToEdit] = useState(null); + const [sortBy1, setSortBy1] = useState("dueDate"); + const [order1, setOrder1] = useState("asc"); + const [sortBy2, setSortBy2] = useState("priority"); + const [order2, setOrder2] = useState("asc"); + const [averageTimeAll, setAverageTimeAll] = useState(""); + const [averageTimeHigh, setAverageTimeHigh] = useState(""); + const [averageTimeMedium, setAverageTimeMedium] = useState(""); + const [averageTimeLow, SetAverageTimeLow] = useState(""); + const [fetchFlags, setFetchFlags] = useState(true); + const [todoItemsFlags, setTodoItemsFlags] = useState([]); + + // Fetch functions + const fetchTodoItemsFlags = () => { + fetch(`http://localhost:9090/api/todos/colorFlags`) + .then((response) => response.json()) + .then((data) => { + console.log("Todo Items List Flags:", data); + setTodoItemsFlags(data); + }) + .catch((error) => { + console.error('Error fetching todo items:', error); + }); + }; + + const fetchTodoItems = () => { + fetch(`http://localhost:9090/api/todos?name=${name}&priority=${priority}&state=${state}&page=${page}&pageSize=10&sortBy1=${sortBy1}&order1=${order1}&sortBy2=${sortBy2}&order2=${order2}`) + .then((response) => response.json()) + .then((data) => { + console.log("Todo Items List:", data); + setTodoItems(data.items); + setTotalPages(data.totalPages); + }) + .catch((error) => { + console.error('Error fetching todo items:', error); + }); + }; + + const fetchAverageTimes = () => { + fetch('http://localhost:9090/api/todos/averageTime') + .then(response => response.json()) + .then(data => { + setAverageTimeAll(data.averageTimeAll); + setAverageTimeHigh(data.averageTimeHigh); + setAverageTimeMedium(data.averageTimeMedium); + SetAverageTimeLow(data.averageTimeLow); + }) + .catch((error) => { + console.error('Error fetching average times:', error); + }); + }; + + // Effect to fetch data on mount and when dependencies change + useEffect(() => { + if (fetchFlags) { + fetchTodoItemsFlags(); + setFetchFlags(false); + } + + fetchTodoItems(); + fetchAverageTimes(); + if (taskToEdit) { + setTaskName(taskToEdit.name); + setPriorityModal(taskToEdit.priority); + setDueDate(taskToEdit.dueDate); + } else { + setTaskName('Nueva Tarea'); + setPriorityModal('Medium'); + setDueDate(''); + } + }, [page, taskToEdit, sortBy1, sortBy2, order1, order2, fetchFlags]); + + // Sorting functions + const handleSortClick = (field) => { + if (field === sortBy1) { + setOrder1(order1 === "asc" ? "desc" : "asc"); + } else { + setSortBy2(sortBy1); + setOrder2(order1); + setSortBy1(field); + setOrder1("asc"); + } + }; + + const handlePrioritySortClick = () => { + handleSortClick("priority"); + }; + + const handleDueDateSortClick = () => { + handleSortClick("dueDate"); + }; + + // Search function + const handleSearch = () => { + fetchTodoItems(priority, name, state); + setPage(1); + }; + + // Modal handling functions + const handleOpen = () => { + setOpen(true); + }; + + const handleClose = () => { + setOpen(false); + setTaskToEdit(null); // Reset taskToEdit when closing the modal + }; + + // Task handling functions + const handleToggleDone = (id) => { + const newTodoItems = [...todoItems]; + const task = newTodoItems.find((task) => task.id === id); + + if (task) { + task.done = !task.done; + + if (task.done === true) { + updateTaskDone(id, task) + .then(() => { + setTodoItems(newTodoItems); + fetchAverageTimes(); + }) + .catch((error) => { + console.error('Error updating task:', error); + }); + } else { + updateTaskUndone(id, task) + .then(() => { + setTodoItems(newTodoItems); + fetchAverageTimes(); + }) + .catch((error) => { + console.error('Error updating task:', error); + }); + } + } + }; + + const handleSubmit = (event) => { + event.preventDefault(); + const task = { + name: taskName, + priority: priority_Modal, + dueDate: dueDate + }; + + if (taskToEdit && 'id' in taskToEdit) { + updateTask(taskToEdit.id, task) + .then(() => { + setTodoItems(todoItems.map(item => item.id === taskToEdit.id ? { ...item, ...task } : item)); + setTaskToEdit(null); + fetchTodoItems(); + fetchTodoItemsFlags(); + }) + .catch((error) => { + console.error('Error updating task:', error); + }); + } else { + createTask(task) + .then(() => { + fetchTodoItems(); + fetchTodoItemsFlags(); + }) + .catch((error) => { + console.error('Error creating task:', error); + }); + } + + handleClose(); + }; + + // API functions + const createTask = async (todoItem) => { + const response = await fetch(`http://localhost:9090/api/todos`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(todoItem), + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } else { + const data = await response.json(); + console.log(data); + fetchTodoItems(); + } + }; + + const updateTaskDone = async (id, todoItem) => { + const response = await fetch(`http://localhost:9090/api/todos/${id}/done`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(todoItem), + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } else { + const data = await response.json(); + console.log(data); + fetchTodoItems(); + fetchAverageTimes(); + } + }; + + const updateTaskUndone = async (id, todoItem) => { + const response = await fetch(`http://localhost:9090/api/todos/${id}/undone`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(todoItem), + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } else { + const data = await response.json(); + fetchTodoItems(); + fetchAverageTimes(); + console.log(data); + } + }; + + const handleEditClick = (task) => { + setTaskToEdit(task); + setDueDate(task.dueDate); + handleOpen(); + }; + + const updateTask = async (id, todoItem) => { + const response = await fetch(`http://localhost:9090/api/todos/${id}`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(todoItem), + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } else { + const data = await response.json(); + console.log(data); + fetchTodoItemsFlags(); + fetchTodoItems(); + } + }; + + const deleteTask = async (id) => { + const response = await fetch(`http://localhost:9090/api/todos/${id}`, { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } else { + setTodoItems(todoItems.filter(task => task.id !== id)); + console.log(`Task with id ${id} deleted.`); + fetchTodoItemsFlags(); + fetchTodoItems(); + fetchAverageTimes(); + } + }; + + return { + todoItems, setTodoItems, page, setPage, totalPages, setTotalPages, name, setName, priority, setPriority, state, setState, label, setLabel, open, setOpen, dueDate, setDueDate, taskName, setTaskName, priority_Modal, setPriorityModal, taskToEdit, setTaskToEdit, sortBy1, setSortBy1, order1, setOrder1, sortBy2, setSortBy2, order2, setOrder2, averageTimeAll, setAverageTimeAll, averageTimeHigh, setAverageTimeHigh, averageTimeMedium, setAverageTimeMedium, averageTimeLow, SetAverageTimeLow, fetchFlags, setFetchFlags, todoItemsFlags, setTodoItemsFlags, handleOpen, handleClose, handleToggleDone, handleSubmit, handleSearch, handlePrioritySortClick, handleDueDateSortClick, handleEditClick, deleteTask, updateTask, createTask, updateTaskDone, updateTaskUndone, fetchTodoItemsFlags, fetchTodoItems, fetchAverageTimes, handleSortClick + }; +}; \ No newline at end of file