import React, { useState,useEffect } from 'react';
import { gameInfo } from '../../services/ggsh.service';
import Loading from '../loading.component';
import PlayerScores from "./player-score-list.component";

const PlayerScoresContainer = ({ gameId, onReturnToStart }) => {
  const [scores, setScores] = useState(null);

  useEffect(() => {
    // define how to fetch scores
    const fetchInfo = async () => {
      const { players } = await gameInfo(gameId);
      setScores(players);
    };
    // when the component renders, fetch the game info
    fetchInfo();
    // and do it again every 5 seconds after
    const interval = setInterval(() => fetchInfo(), 5000);
    // and return a clean-up callback
    return () => { clearInterval(interval) };
  }, [gameId]);

  if (!scores) {
    return <Loading/>
  }

  return (
    <div>
      <p>Previous Game:</p>
      <PlayerScores scores={scores} />
      <button onClick={onReturnToStart} >Return to Start</button>
    </div>
  );
}

export default PlayerScoresContainer;
