2021-09-18 13:31:05 +00:00
|
|
|
import React, { createContext, useEffect } from "react"
|
2021-09-19 03:47:46 +00:00
|
|
|
import {
|
|
|
|
AT,
|
|
|
|
getUser,
|
|
|
|
userObjIsEqual,
|
|
|
|
} from "@lingdocs/lingdocs-main";
|
2022-04-08 10:41:11 +00:00
|
|
|
import {
|
|
|
|
useStickyState,
|
2022-10-10 10:06:32 +00:00
|
|
|
} from "@lingdocs/ps-react";
|
2021-09-18 13:19:44 +00:00
|
|
|
import { CronJob } from "cron";
|
2021-09-21 16:45:09 +00:00
|
|
|
import { postSavedResults } from "./lib/game-results";
|
2021-09-18 04:43:00 +00:00
|
|
|
|
|
|
|
const UserContext = createContext<
|
2021-09-18 13:11:08 +00:00
|
|
|
{
|
|
|
|
user: AT.LingdocsUser | undefined,
|
|
|
|
setUser: React.Dispatch<React.SetStateAction<AT.LingdocsUser | undefined>>,
|
|
|
|
pullUser: () => void,
|
|
|
|
}
|
2021-09-18 04:43:00 +00:00
|
|
|
| undefined
|
|
|
|
>(undefined);
|
|
|
|
|
2021-09-18 13:19:44 +00:00
|
|
|
// TODO: persisting user in local state
|
2021-09-18 04:43:00 +00:00
|
|
|
function UserProvider({ children }: any) {
|
2021-11-04 00:09:42 +00:00
|
|
|
const [value, setValue] = useStickyState<AT.LingdocsUser | undefined>(
|
2021-09-18 22:22:47 +00:00
|
|
|
undefined,
|
|
|
|
"saved-user",
|
|
|
|
);
|
2021-09-18 13:11:08 +00:00
|
|
|
|
|
|
|
function pullUser() {
|
|
|
|
getUser().then((user) => {
|
2021-09-19 03:47:46 +00:00
|
|
|
if (user === "offline") return;
|
|
|
|
// don't update if there's nothing new - to avoid re-renders erasing game input etc
|
|
|
|
if (!userObjIsEqual(user, value)) {
|
|
|
|
setValue(user);
|
|
|
|
}
|
2021-09-18 13:11:08 +00:00
|
|
|
}).catch(console.error);
|
|
|
|
}
|
|
|
|
|
2022-05-10 21:48:13 +00:00
|
|
|
const checkUserCronJob = new CronJob("10 * * * *", () => {
|
2021-09-18 13:19:44 +00:00
|
|
|
pullUser();
|
2021-09-21 16:45:09 +00:00
|
|
|
if (value) {
|
|
|
|
postSavedResults(value.userId);
|
|
|
|
}
|
2021-09-18 13:19:44 +00:00
|
|
|
});
|
|
|
|
|
2021-09-18 13:11:08 +00:00
|
|
|
useEffect(() => {
|
|
|
|
pullUser();
|
2021-09-18 13:19:44 +00:00
|
|
|
checkUserCronJob.start();
|
|
|
|
return () => {
|
|
|
|
checkUserCronJob.stop();
|
|
|
|
}
|
|
|
|
// eslint-disable-next-line
|
2021-09-18 13:11:08 +00:00
|
|
|
}, []);
|
|
|
|
|
2021-09-18 13:31:05 +00:00
|
|
|
return <UserContext.Provider value={{ user: value, setUser: setValue, pullUser }}>
|
2021-09-18 04:43:00 +00:00
|
|
|
{children}
|
|
|
|
</UserContext.Provider>;
|
|
|
|
}
|
|
|
|
|
|
|
|
function useUser() {
|
|
|
|
const context = React.useContext(UserContext)
|
|
|
|
if (context === undefined) {
|
2021-09-18 13:31:05 +00:00
|
|
|
throw new Error('useUser must be used within a UserProvider')
|
2021-09-18 04:43:00 +00:00
|
|
|
}
|
|
|
|
return context;
|
|
|
|
}
|
|
|
|
|
|
|
|
export { UserProvider, useUser };
|