import React from 'react';
import { gameInfo } from '../services/ggsh.service';
import Loading from './loading.component';

// TODO render this as a nice score page
// TODO live updates?

const PlayerScores = ({ scores }) => (
  <div style={{
    display: "flex", 
    flexFlow: "row wrap", 
    justifyContent: "space-around", 
    alignItems: "center", 
    alignContent: "space-around"}}>
    {
      scores
        .filter(({ currentRound }) => currentRound === null)
        .sort((p1, p2) => p1.totalScore > p2.totalScore ? -1 : (p1.totalScore < p2.totalScore ? 1 : 0))
        .map(({ name, guesses, totalScore }) => 
          <div style={{flex: 1}}>
            <p>{name}</p>
            <p>Score: {totalScore}</p>
            <ol>
              <li>{guesses["1"] && guesses["1"].score}</li>
              <li>{guesses["2"] && guesses["2"].score}</li>
              <li>{guesses["3"] && guesses["3"].score}</li>
              <li>{guesses["4"] && guesses["4"].score}</li>
              <li>{guesses["5"] && guesses["5"].score}</li>
            </ol>
          </div>
        )
    }
  </div>
);

class PlayerScoresContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { scores: null }
  }

  async componentDidMount() {
    const { gameId } = this.props;
    const { players } = await gameInfo(gameId);
    this.setState({ scores: players });
  }

  render() {
    const { scores } = this.state;
    if (!scores) {
      return <Loading/>
    }

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

}

export default PlayerScoresContainer;
