|
| 1 | +import { useContext, useState, useEffect } from 'react'; |
| 2 | +import { TimetableInput } from '~/types/typedef'; |
| 3 | +import { UserCredentialsContext } from './UserCredentialsContext'; |
| 4 | +import { timetableHistoryCol } from '~/lib/firebase'; |
| 5 | +import { doc, getCountFromServer, query, serverTimestamp, setDoc, where } from 'firebase/firestore'; |
| 6 | + |
| 7 | +const STORAGE_KEY = 'TIME_TABLE_HISTORY'; |
| 8 | + |
| 9 | +interface UseTimetableHistory { |
| 10 | + payload: TimetableInput; |
| 11 | + created_at: string; |
| 12 | + hash: string; |
| 13 | +} |
| 14 | + |
| 15 | +const useTimetableHistory = (): [ |
| 16 | + UseTimetableHistory[], |
| 17 | + (timetable: UseTimetableHistory) => void |
| 18 | +] => { |
| 19 | + const user = useContext(UserCredentialsContext); |
| 20 | + const [timetableHistory, setTimetableHistory] = useState<UseTimetableHistory[]>([]); |
| 21 | + |
| 22 | + useEffect(() => { |
| 23 | + const storedTimetableHistory = localStorage.getItem(STORAGE_KEY); |
| 24 | + if (storedTimetableHistory) setTimetableHistory(JSON.parse(storedTimetableHistory)); |
| 25 | + }, []); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + if (user == null || user.user == null) return; |
| 29 | + |
| 30 | + const timetableHistoryQuery = query( |
| 31 | + timetableHistoryCol, |
| 32 | + where('email', '==', user.user?.email) |
| 33 | + ); |
| 34 | + |
| 35 | + const email = user.user.email as string; |
| 36 | + |
| 37 | + getCountFromServer(timetableHistoryQuery).then((snapShot) => { |
| 38 | + const count = snapShot.data().count; |
| 39 | + if (count !== 0) return; |
| 40 | + |
| 41 | + timetableHistory.forEach((history) => { |
| 42 | + setDoc(doc(timetableHistoryCol), { |
| 43 | + payload: history.payload, |
| 44 | + email: email, |
| 45 | + createdAt: serverTimestamp() |
| 46 | + }); |
| 47 | + }); |
| 48 | + }); |
| 49 | + |
| 50 | + return () => {}; |
| 51 | + }, [user, timetableHistory]); |
| 52 | + |
| 53 | + const addTimetableHistory = (timetable: UseTimetableHistory) => { |
| 54 | + setTimetableHistory((prev) => { |
| 55 | + const isAlreadyInHistory = prev.some((history) => history.hash === timetable.hash); |
| 56 | + if (isAlreadyInHistory) return prev; |
| 57 | + const newTimetableHistory = [timetable, ...prev]; |
| 58 | + if (newTimetableHistory.length > 50) newTimetableHistory.pop(); |
| 59 | + localStorage.setItem(STORAGE_KEY, JSON.stringify(newTimetableHistory)); |
| 60 | + return newTimetableHistory; |
| 61 | + }); |
| 62 | + }; |
| 63 | + |
| 64 | + return [timetableHistory, addTimetableHistory]; |
| 65 | +}; |
| 66 | + |
| 67 | +export default useTimetableHistory; |
0 commit comments