components/Modals/LiveFinish.js

/**
 * @module Modals/LiveFinish
 */
import React, { Component } from 'react';
import Constants, { SVG_ICONS } from '../../constants';
import { remapMarketsToSelectionWinningScores } from '../../utils/common';
import SVGComponent from '../SVG/SVGComponent';
/**
 * @typedef {object} props
 * @property {ModalData} modalData
 * @property {string} currentPage
 * @property {Function} changePage
 * @property {Function} closeModal
 */
/**
 * @typedef {object} ModalData
 * @property {number} round
 * @property {number} liveRound
 * @property {string} gameType
 */
export default class LiveFinish extends Component {
  constructor() {
    super();

    /**
     * @member {object}
     * @property {boolean} autoredirect Represent timer in modal
     */
    this.state = { autoredirect: 10, wonBetsCount: -1 };
  }

  /**
   * Start auto redirection timer
   *
   * @returns {void}
   */
  componentDidMount() {
    this.countdownInterval = setInterval(() => {
      if (this.state.autoredirect > 0) {
        this.setState({ autoredirect: this.state.autoredirect - 1 });
      } else {
        this.endLiveAndNavigate();
      }
    }, 1000);

    this.wonBetTimeout = setTimeout(this.countWonBets, 0);
  }

  /**
   * Go to BETS page and clear interval
   *
   * @returns {void}
   */
  componentWillUnmount() {
    clearTimeout(this.wonBetTimeout);
    clearInterval(this.countdownInterval);
    if (this.state.autoredirect <= 0) {
      this.props.changePage({
        page: Constants.PAGES.BETS,
      });
    }
    this.props.removePlacedBets({ roundId: this.props.liveId });
  }

  /**
   * count won bets
   *
   * @returns {void}
   */
  countWonBets = () => {
    let result = 0;
    const { scores, markets, placedBets } = this.props;
    const selectionWinningScoreMap = remapMarketsToSelectionWinningScores(markets);
    for (let i = 0; i < placedBets.length; i += 1) {
      const bet = placedBets[i];
      const minToWin = bet.group;
      const selections = bet.selections;
      const wonMatchMap = {};
      for (let j = 0; j < selections.length; j += 1) {
        const selectionData = selections[j];
        const [league, match, selection] = selectionData.split(':');
        const homeTeamIndex = match * 2 - 2;
        const awayTeamIndex = homeTeamIndex + 1;
        const score = `${scores[league][homeTeamIndex]}:${scores[league][awayTeamIndex]}`;
        const winningScores = selectionWinningScoreMap[selection];
        const won = winningScores.indexOf(score) !== -1;
        if (won) {
          wonMatchMap[`${league}-${match}`] = true;
        }
      }
      if (Object.keys(wonMatchMap).length >= minToWin) {
        result += 1;
      }
    }
    this.setState({ wonBetsCount: result });
  }

  /**
   * finish live, close modal and navigate from page
   *
   * @param {string} page
   * @returns {void}
   */
  endLiveAndNavigate = (page) => {
    this.props.liveFinished({ gameType: this.props.modalData.gameType });
    this.props.closeModal();
    this.props.changePage({ page: (page || Constants.PAGES.BETS) });
  };

  /**
   * RenderRedirectButton
   *
   * @param {number} wonBetsCount
   * @returns {void}
   */
  renderRedirectButton = (wonBetsCount) => {
    if (wonBetsCount < 0) {
      return null;
    }

    if (wonBetsCount === 0) {
      return (
        <button
          className="btn btn-light btn-block"
          type="button"
          onClick={this.endLiveAndNavigate.bind(this, Constants.PAGES.RESULTS)}
        >
          View Results
          <SVGComponent
            className="icon-m arrow-right"
            src={`${SVG_ICONS.utility}#icon__arrow`}
          />
        </button>
      );
    }

    return (
      <button
        type="button"
        className="btn btn-secondary btn-block"
        id="winningBetsBtn"
        onClick={this.endLiveAndNavigate.bind(this, Constants.PAGES.TICKETS)}
      >
        View
        {' '}
        <span className="week-complete__win-bet">{wonBetsCount}</span>
        {wonBetsCount === 1 ? ' Winning Bet' : ' Winning Bets'}
        <SVGComponent
          className="icon-m arrow-right"
          src={`${SVG_ICONS.utility}#icon__arrow`}
        />
      </button>
    );
  }

  /**
   * render header
   *
   * @param {number} wonBetsCount
   * @returns {void}
   */
  renderHeader = (wonBetsCount) => (
    <div className="px-10">
      {wonBetsCount > 0 && <div className="week-complete__icon" />}
      <div className="week-complete__txt">Round Over !</div>
      {wonBetsCount > 0 && <div className="week-complete__bets">{`Congratulations You won ${wonBetsCount} bet${wonBetsCount > 1 ? 's' : ''}`}</div>}
    </div>
  );

  /**
   * Render
   *
   * @returns {view}
   */
  render() {
    return (
      <div className="loader">
        <div className={`week-complete ${this.state.wonBetsCount > 0 ? 'week-complete--won' : ''}`}>
          {this.renderHeader(this.state.wonBetsCount)}
          <div className="week-complete__heading">
            <span>{`Week ${this.props.modalData.liveRound}`}</span>
            <span className="vertical-spacer" />
            Complete
          </div>
          <div className="px-10">
            {this.renderRedirectButton(this.state.wonBetsCount)}
            <button
              className="btn btn-primary btn-block"
              onClick={this.endLiveAndNavigate.bind(this, Constants.PAGES.BETS)}
              type="button"
            >
              Odds for Week
              {' '}
              {this.props.modalData.round}
              {' '}
              ( in
              {' '}
              {this.state.autoredirect}
              ... )
              <SVGComponent
                className="icon-m arrow-right"
                src={`${SVG_ICONS.utility}#icon__arrow`}
              />
            </button>
          </div>
        </div>
      </div>
    );
  }
}