6080-a3-BigBrain / frontend / src / FrontendPages / ResultsPage.jsx
ResultsPage.jsx
Raw
import React, { useState, useEffect } from 'react'
import gameService from '../BackendRequests/gameData';
import PropTypes from 'prop-types'
import { useParams, Link as URLlink } from 'react-router-dom'
import {
  Box, Typography, TableContainer, Table, TableHead, TableRow, TableBody, TableCell, Button
} from '@mui/material'
import { Bar } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

const style = {
  position: 'absolute',
  top: '1%',
  backgroundColor: '#a2627c',
  '&:hover': {
    background: '#a2627c',
  }
}
const ResultsPage = () => {
  const [results, setResults] = useState('')
  const resultsId = useParams().resultId;
  const quizId = useParams().gId;
  const [allAnswers, setAllAnswers] = useState([])
  const [score, setScore] = useState([])
  const [questionNum, setQuestionNum] = useState([])
  // const [lengthQ, setLengthQ] = useState(0)
  console.log(resultsId)
  const [displayUsers, setDisplayUsers] = useState([])

  useEffect(() => {
    console.log('here')
    console.log(resultsId)
    const token = localStorage.getItem('token')
    let i = 0;
    let a = 0;
    const getResults = async () => {
      const pointsArray = await gameService.getPoints(token, quizId)
      console.log(pointsArray)

      await gameService.getQuizAdminResult(token, resultsId)
        .then(res => {
          setResults(res.results)
          console.log(res.results)
          const length = res.results[0].answers.length; // add +1 for every correct answer of given question
          // setLengthQ(length)
          const questionArray = Array.from(Array(length).keys())
          const questionsCorrect = Array(length).fill(0);
          const players = Array(res.results.length).fill(0);
          console.log(players)
          const playerNames = Array(res.results.length).fill('');
          // setScore(players)
          // console.log(score)
          console.log(questionsCorrect)
          setQuestionNum(questionArray)
          res.results.map(player => {
            i = 0;
            console.log(player.name)
            playerNames[a] = player.name
            setResults(res)
            player.answers.map(answer => {
              if (answer.correct) {
                console.log(answer.correct)
                questionsCorrect[i] = questionsCorrect[i] + 1
                console.log(questionsCorrect)
                players[a] = players[a] + pointsArray[i]
              }
              console.log(i)
              console.log(players)
              i++
              return questionsCorrect;
            })
            a++
            return results;
          })
          setAllAnswers(questionsCorrect)
          setDisplayUsers(playerNames)
          console.log(score)
          setScore(players)
        })
    }
    getResults();
  }, []);

  const correctAnswersChart = {
    labels: questionNum,
    datasets: [
      {
        label: 'Players who answered question# correctly',
        backgroundColor: 'rgba(75,192,192,1)',
        borderColor: 'rgba(0,0,0,1)',
        borderWidth: 1,
        data: allAnswers
      }
    ]
  }
  const pointsChart = {
    labels: displayUsers,
    datasets: [
      {
        label: 'Player scores',
        backgroundColor: 'rgba(75,192,192,1)',
        borderColor: 'rgba(0,0,0,1)',
        borderWidth: 1,
        data: score
      }
    ]
  }
  if (results != null) {
    const list = results
    return (
    <>
      <Button component={URLlink} to="/dashboard" variant="contained" sx={style} left='8%' className="backToDashboard">
        &lt; Back to dashboard
      </Button>
      <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        height: '50%',
        width: '50%',
        marginLeft: '25%'
      }}>
        <Typography display="center"><h1>Results of Quiz Game</h1></Typography>
        <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell><h3>User</h3></TableCell>
                  <TableCell><h3>Questions answered correctly</h3></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {list.results && list.results.map((user) => (
                  <TableRow key={user}>
                    <TableCell>{user.name}</TableCell>
                    <TableCell>{user.answers && user.answers.map((answer) => (
                      <TableRow key={answer}>
                        <TableCell>{(answer.correct === true) && <h4>Correct</h4>}</TableCell>
                      </TableRow>
                    ))}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        <Bar
          data={correctAnswersChart}
          options={{
            title: {
              display: true,
              text: 'Players who answered questions correctly',
              fontSize: 20
            },
            legend: {
              display: true,
              position: 'right'
            },
            barPercentage: 0.2
          }}
        />
        <Bar
          data={pointsChart}
          options={{
            title: {
              display: true,
              text: 'Player scores',
              fontSize: 20
            },
            legend: {
              display: true,
              position: 'right'
            },
            barPercentage: 0.2
          }}
        />
      </Box>
      </>
    )
  }
}

export default ResultsPage
ResultsPage.propTypes = {
  resultsId: PropTypes.object
}