import { createContext, FC, ReactNode, useContext, useState } from "react"; import {IToDo, REPEAT_TYPE} from "@/hooks/firebase/types/todoData"; import {useGetTodos} from "@/hooks/firebase/useGetTodos"; import {useCreateTodo} from "@/hooks/firebase/useCreateTodo"; import {useUpdateTodo} from "@/hooks/firebase/useUpdateTodo"; const initialTodosList = [ { id: 0, title: "Pay: Credit card", done: false, date: new Date(), rotate: true, repeatType: "Every week", }, { id: 1, title: "Monthly Log story", done: false, date: new Date(), rotate: false, repeatType: "Every week", }, { id: 2, title: "Write: Arcade Highlights", done: false, date: new Date(), rotate: true, repeatType: "Every week", }, { id: 3, title: "Dressup: Cat", done: false, date: new Date(Date.now() + 86400000), points: 40, rotate: false, repeatType: "Every week", }, { id: 4, title: "Trim: Nails", done: false, date: new Date(Date.now() + 86400000), rotate: false, repeatType: "Once a Month", }, { id: 5, title: "Monthly Log", done: false, date: new Date(Date.now() + 2 * 86400000), rotate: true, repeatType: "Once a Month", }, { id: 6, title: "Do it", done: false, date: new Date(Date.now() + 3 * 86400000), rotate: false, repeatType: "Once a year", points: 50, }, { id: 7, title: "Buy Nautica Voyage", done: false, date: null, rotate: false, repeatType: "None", }, { id: 8, title: "Sell Dan's Xbox", done: false, date: null, rotate: false, repeatType: "None", points: 10, }, ]; export const repeatOptions = [ { label: REPEAT_TYPE.NONE, value: REPEAT_TYPE.NONE }, { label: REPEAT_TYPE.DAILY, value: REPEAT_TYPE.DAILY}, { label: REPEAT_TYPE.EVERY_WEEK, value: REPEAT_TYPE.EVERY_WEEK }, { label: REPEAT_TYPE.ONCE_A_MONTH, value: REPEAT_TYPE.ONCE_A_MONTH }, { label: REPEAT_TYPE.ONCE_A_YEAR, value: REPEAT_TYPE.ONCE_A_YEAR }, ]; interface IToDosContext { toDos: IToDo[]; updateToDo: (changes: Partial) => void; addToDo: (newToDo: IToDo) => void; maxPoints: number; } const ToDosContext = createContext(undefined!); export const ToDosContextProvider: FC<{ children: ReactNode }> = ({ children, }) => { const { data: toDos } = useGetTodos(); const { mutateAsync: createTodo } = useCreateTodo(); const { mutateAsync: updateTodo } = useUpdateTodo(); const initCalc = (): number => { return (toDos ?? []).reduce( (sum, todo) => sum + (todo.points ? todo.points : 0), 50 ); }; const calculateMaxPoints = () => { let totalPoints = 0; if (toDos) { totalPoints = toDos.reduce( (sum, todo) => sum + (todo.points ? todo.points : 0), 0 ); } setMaxPoints(totalPoints); }; const [maxPoints, setMaxPoints] = useState(initCalc); const updateToDo = (changes: Partial) => { updateTodo(changes).then(calculateMaxPoints); }; const addToDo = (newToDo: IToDo) => { createTodo(newToDo).then(calculateMaxPoints); }; return ( {children} ); }; export const useToDosContext = () => useContext(ToDosContext)!;