diff --git a/src/context/GameContext.js b/src/context/GameContext.js index fb8d490..f314052 100644 --- a/src/context/GameContext.js +++ b/src/context/GameContext.js @@ -1,13 +1,16 @@ import { createContext, useContext, useEffect, useState } from "react"; import chantierAtmopshere from "../assets/sounds/chantier_1.mp3"; import GameAnswerExplanation from "../components/game/GameAnswerExplanation.jsx"; -import { useGame } from "../hooks/useGame.jsx"; import { useUser } from "../hooks/useUser.jsx"; import { calculateScore } from "../utils/gameFunctions.js"; +import { postGameStatisticsData } from "../services/WordpressFetchData.js"; +import { useNavigate } from "react-router-dom"; export const GameContext = createContext(); export function GameContextProvider({ children }) { + const navigate = useNavigate(); + const { language, country } = useUser(); // ##### DATA ##### @@ -16,6 +19,7 @@ export function GameContextProvider({ children }) { // ##### GAME ##### const [answers, setAnswers] = useState(null); const [score, setScore] = useState(null); + const [gameTime, setGameTime] = useState(0); // ##### INTERFACE ##### const [hasCheckedTutorial, setHasCheckedTutorial] = useState(false); @@ -26,7 +30,7 @@ export function GameContextProvider({ children }) { const [isTimeRuning, setIsTimeRuning] = useState(false); const [isGameComplete, setIsGameComplete] = useState(false); - // INIT DATAS + // ##### INIT DATAS ##### useEffect(() => { if (!contextGameDatas) return; initAnswers(); @@ -58,14 +62,32 @@ export function GameContextProvider({ children }) { function checkIfGameIsComplete() { const isGameFinished = answers.every((answer) => answer.userAnswer !== null); if (!isGameFinished) return; - console.warn(answers); - alert("Game is complete"); + endGame(); + } + + function endGame() { + console.log("### Edning Game is complete"); setIsTimeRuning(false); setIsGameComplete(true); + const gameStats = buildGameStatsObject(); + postGameStatisticsData(gameStats); + // navigate("/results"); + navigate("/results", { state: { gameStats, contextGameDatas } }); + } + + function buildGameStatsObject() { + if (!language || !country || !country.name || !contextGameDatas.gameId) return null; + return { + user_locale: language, + user_country: country.name, + level_post_id: contextGameDatas.gameId ?? null, + level_score: score ?? 0, + level_completion_time: gameTime, + }; } function resetGame() { - isGameComplete(false); + setIsGameComplete(false); setIsTimeRuning(false); } @@ -74,6 +96,9 @@ export function GameContextProvider({ children }) { value={{ currentGameModal, score, + + gameTime, + setGameTime, setCurrentGameModal, contextGameDatas, setContextGameDatas, @@ -81,10 +106,12 @@ export function GameContextProvider({ children }) { setIsTimeRuning, isGameComplete, answers, + resetGame, setAnswers, initAnswers, isSoundOn, setIsSoundOn, + buildGameStatsObject, answerQuestion, hasCheckedTutorial, setHasCheckedTutorial,