// EditQuestionPage.jsx - new file in BackendRequests import { Link as URLlink, useNavigate, useParams } from 'react-router-dom' import React, { useState, useEffect } from 'react' import gameDataService from '../BackendRequests/gameData' import { Box, Button, Typography, CssBaseline, Paper, TextField, Input, Link, MenuItem, Select } from '@mui/material' import loginService from '../BackendRequests/login' import editGameService from '../BackendRequests/editGame' import { fileToDataUrl } from '../helpers' const style = { position: 'absolute', top: '1%', backgroundColor: '#a2627c', '&:hover': { background: '#a2627c', } } const saveButtonStyle = { mt: 3, backgroundColor: '#d0605e', '&:hover': { background: '#d0605e', } } const addMoreButtonStyle = { color: 'white', backgroundColor: '#d0605e', '&:hover': { background: '#d0605e', }, mt: 1, } const EditQuestionPage = () => { const questionId = useParams().qId; console.log(questionId) const [questions, setQuestions] = useState({}); const gameId = useParams().gId; const token = localStorage.getItem('token'); const [content, setContent] = useState(''); const [points, setPoints] = useState(0); const [timeLimit, setTimeLimit] = useState(0); const [questionType, setQuestionType] = useState('Single Choice'); const [answers, setAnswers] = useState([{ answerNum: 1, answerText: '', isCorrect: false }, { answerNum: 2, answerText: '', isCorrect: false }]); const [attachmentType, setAttachmentType] = useState(''); const [picture, setPicture] = useState(''); const [vidUrl, setVidUrl] = useState(''); let [qList, setQList] = useState([]); const navigate = useNavigate() useEffect(() => { gameDataService.getQuestionData(token, gameId, questionId) .then((res) => { setQuestions(res[0]); console.log(res[0].content); setContent(res[0].content); setPoints(res[0].points); setTimeLimit(res[0].timeLimit); setQuestionType(res[0].questionType); if (res[0].answers.length !== 0) setAnswers(res[0].answers) }) }, []) console.log(questions) useEffect(() => { gameDataService.getQuizData(token, gameId) .then((res) => { console.log(res.questions) setQList(res.questions); }) }, []) const handleEdit = async () => { const newQ = { ...questions, points: points, content: content, timeLimit: timeLimit, attachmentType: attachmentType, picture: picture, video: vidUrl, questionType: questionType, answers: answers, }; setQuestions(newQ); console.log(newQ) console.log(qList) const newArray = qList.filter((item) => { console.log(item.qId) return Math.abs(item.qId - questionId) !== 0 }) console.log(newArray) qList.splice(0, qList.length) console.log(qList) qList = newArray console.log(qList) const newQuestions = [...qList]; newQuestions.push(newQ); console.log(qList) qList.push(newQ) console.log(qList) // setQList(newQuestions); const res = await editGameService.editQuiz( token, gameId, qList, '', '' ) console.log(res) navigate(`/edit/game/${gameId}`) } const email = localStorage.getItem('email'); const logoutButton = async () => { try { console.log(email); await loginService.logout(email); localStorage.removeItem('token'); } catch (err) { console.log(err); } } const handleAnswers = (event, answer) => { const newText = event.target.value; console.log(newText); const newAnswers = [...answers]; const answerIndex = newAnswers.findIndex(a => a.answerNum === answer.answerNum); newAnswers[answerIndex] = { answerNum: answer.answerNum, answerText: newText, isCorrect: answer.isCorrect, }; setAnswers(newAnswers); console.log(answers); } const uploadPicture = async (e) => { const picUrl = await fileToDataUrl(e.target.files[0]); setPicture(picUrl); } // const [correctState, setCorrectState] = useState(false); const handleCorrectAnswer = (e, answer) => { const isChecked = e.target.checked; const newAnswers = [...answers]; const answerIndex = newAnswers.findIndex(a => a.answerNum === answer.answerNum); newAnswers[answerIndex].isCorrect = isChecked; setAnswers(newAnswers); } const handleAddAnswer = (answers) => { const lastNum = answers[answers.length - 1].answerNum; console.log(lastNum); const newAnswers = [...answers]; newAnswers.push({ answerNum: lastNum + 1, answerText: '', isCorrect: false }); setAnswers(newAnswers); } // TODO: // - enforce question to have at least one correct answers // - Add more answer button, maximum 6 answers. return ( <> <Button component={URLlink} to="/dashboard" variant="contained" sx={style} left='8%' className="backToDashboard"> < Back to dashboard </Button> <Box component="form" sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', backgroundColor: '#F5F5F5', }}> <CssBaseline /> <Paper style={{ display: 'grid', gridRowGap: '10px', padding: '20px', paddingLeft: '100px', paddingRight: '100px' }}> <Typography fontWeight='bold'>Question:</Typography> <TextField type="text" label={content} onChange={e => setContent(e.target.value)} /> <Typography fontWeight='bold' style={{ marginTop: '8px' }} className="pointsCurrent"> Points Currently: {points}</Typography> <TextField type="number" label={points} onChange={e => setPoints(e.target.value)} className="pointsInput" /> <Typography fontWeight='bold' className="timeCurrent" style={{ marginTop: '8px' }}>Time Limit Currently: {timeLimit} </Typography> <TextField type="number" label={timeLimit} className="timeInput" onChange={e => setTimeLimit(e.target.value)} /> <Typography fontWeight='bold'>Add picture or YouTube URL to enhance your quiz (Optional): </Typography> <div> <Select defaultValue={attachmentType} onChange={e => setAttachmentType(e.target.value)}> <MenuItem value="None" selected>None</MenuItem> <MenuItem value="Picture">Picture</MenuItem> <MenuItem value="Video">Youtube Link</MenuItem> </Select> </div> {attachmentType === 'Picture' ? <div> <img src={picture} width="120" height="120"></img> <br /> <Input type='file' onChange={(e) => uploadPicture(e)} /> <br /> </div> : attachmentType === 'Video' ? <div> <Link>{vidUrl}</Link> <br /> <TextField type="text" label="Add link to your video here" onChange={e => setVidUrl(e.target.value)}> </TextField> </div> : <div>None Chosen</div>} <Typography fontWeight='bold' className="typeCurrent">Question Type Currently: {questionType}</Typography> <div> <Select defaultValue={questionType} onChange={e => setQuestionType(e.target.value)} className="typeInput"> <MenuItem value="Single Choice">Single Choice</MenuItem> <MenuItem value="Multiple Choice">Multiple Choice</MenuItem> </Select> </div> <Typography fontWeight='bold' style={{ marginTop: '8px' }}> <Typography fontWeight='bold'>Answers: </Typography> {questionType === 'Multiple Choice' ? ( <form> {answers.map((answer) => { // answer.isCorrect = false; return ( <> <TextField key={answer.answerNum} type="text" label={answer.answerText} onChange={e => handleAnswers(e, answer)} /> <input type="checkbox" onChange={(e) => handleCorrectAnswer(e, answer)} name="singleChoiceQ" checked={answer.isCorrect} // onClick={(e) => { if (e.target.checked) answer.isCorrect = true } /> <br /> </> ) })} </form> ) : ( <form> {answers.map((answer) => { // answer.isCorrect = false; return ( <> <TextField key={answer.answerNum} type="text" label={answer.answerText} onChange={e => handleAnswers(e, answer)} /> <input type="radio" onChange={(e) => handleCorrectAnswer(e, answer)} name="singleChoiceQ" value={answer.isCorrect} // onClick={(e) => { if (e.target.checked) answer.isCorrect = true } /> <br /> </> ) })} </form> ) } {answers.length < 6 ? (<Button type="button" sx={addMoreButtonStyle} onClick={() => handleAddAnswer(answers)}>Add More</Button>) : <></> } </Typography> <Button variant="contained" sx={saveButtonStyle} onClick={handleEdit} className="saveQuestion" > Save Changes </Button> </Paper> </Box> { <Button component={URLlink} style={{ position: 'absolute', right: 0, top: '1%' }} onClick={logoutButton} to="/login" variant="contained" sx={style}> LOGOUT </Button> } </> ) } export default EditQuestionPage;