import { h, render, Component } from 'preact'; // eslint-disable-line no-unused-vars
import DonutGraphItem from './partials/DonutGraphItem.jsx';

// render the current score including animated donut graph
export default class ScoreScreen extends Component {

  // construct properties
  constructor (props) {
    super(props);
    this.state = {
      myScore: this.getMyScore(),
      otherUsersScore: this.getOtherUsersScore()
    };
  }

  // get score from current user
  getMyScore () {
    let numberCorrect = 0;

    [ ...this.props.answers ].forEach(item => {
      numberCorrect += item.isCorrect ? 1 : 0;
    });
    return numberCorrect / this.props.answers.length;
  }

  // get score from other users
  getOtherUsersScore () {
    let sum = 0;

    [ ...this.props.voteStats ].forEach(stat => {
      sum += stat;
    });
    return sum / this.props.voteStats.length;
  }

  // LIFECYLCE methods
  componentDidMount () {
    if (this.props.answers.length >= this.props.numberQuestions) this.props.endUserSession();
  }

  // ... and render it
  render () {
    const isLast = this.props.answers.length >= this.props.numberQuestions;

    return (
      <section className="wrapper  wrapper__score">
        <main className="wrapper__main  wrapper--centered">
          <div className="score-item">
            <span className="text-min-mod1">
              { isLast ? this.props.endscorelabel : this.props.interimscorelabel }
            </span>
            <span className="number--huge  number--huge--spaced">{Math.round(this.state.myScore * 100)}%</span> korrekt.
            <DonutGraphItem endval={this.state.myScore} />
          </div>
          { !this.props.isOffline
            ? <div className="score-item">
              <span className="text-min-mod1">{this.props.othersscorelabel}</span>
              <span className="number--huge  number--huge--spaced">{Math.round(this.state.otherUsersScore * 100)}%</span> korrekt.
              <DonutGraphItem endval={this.state.otherUsersScore} />
            </div> : [] }
        </main>
        <footer className="footer footer--question">
          { !isLast
            ? <a href="#" title="Start" className="button--wide" onClick={ this.props.newQuestion }>{this.props.next}</a>
            : <a href="#" title="Start" className="button--wide" onClick={ this.props.reset }>Zum Start</a> }
        </footer>
      </section>
    );
  }

}
