import React, { Component, Fragment } from 'react';

import LeaderCard from './leader-card.jsx';
import GameLeaderTogglePanel from './game-leader-toggle-panel.jsx';
import InjuryCard from './injury-card.jsx';
import TeamStatCard from './team-stat-card.jsx';
import GameHeader from './game-header.jsx';
import GameArticlePreview from './game-article-preview.jsx';
import MatchupPredictor from './matchup-predictor.jsx';

import FootballScoringSummary from './football-scoring-summary.jsx';

import GameInfo from './game-info.jsx';
import Standings from './standings.jsx';
import PickCenter from './pick-center.jsx';

import Card from '@material-ui/core/Card';
import PieChart from './pie-chart.jsx';
import LineChart from './line-chart.jsx';

const teamData = require('../../config/team-data.json');

const statDataSrc = {
  nfl: [{name: 'totalYards', type: 'line'}, {name: 'turnovers', type: 'line'}, {name: 'possessionTime', type: 'pie'}, {name: 'firstDowns', type: 'line'}],
  nba: [{name: 'fieldGoalPct', type: 'line'}, {name: 'threePointFieldGoalPct', type: 'line'}, {name: 'turnovers', type: 'line'}, {name: 'totalRebounds', type: 'line'}]
};

export default class GamePanel extends Component {
  constructor(props) {
    super();
    this.state = {gameId: null, game: null};
    this.callShowTeam = this.callShowTeam.bind(this);
  }
  
  callShowTeam(ev) {
    const {sport, league} = this.props,
          team = teamData[info.type][league][info.team.id];
    team.sport = info.type;
    team.league = league;
    console.log('click', team, this.state.currTeamData, info);
    this.props.showTeam(team);
  }
  
  componentDidMount() {
    console.log('mounted game panel');
    
    this.state.gameId = this.props.gameId;
    this.fetchGame();
    
    const link1 = document.createElement('link');
    link1.rel = 'stylesheet';
    link1.href = 'css/game-page.css';
    link1.id = 'game-stylesheet-1';
    document.head.appendChild(link1);
    
    const link2 = document.createElement('link');
    link2.rel = 'stylesheet';
    link2.href = 'css/game-package-' + this.props.sport + '.css';
    link2.id = 'game-stylesheet-2';
    document.head.appendChild(link2);
  }
  
  componentDidUpdate(prevProps) {
    if (this.props.gameId !== prevProps.gameId) {
      this.state.gameId = this.props.gameId;
      this.fetchGame();
    }
  }
  
  componentWillUnmount() {
    document.head.removeChild(document.head.querySelector('#game-stylesheet-1'));
    document.head.removeChild(document.head.querySelector('#game-stylesheet-2'));
  }
  
  fetchGame() {
    const {league, sport, id} = this.props;
    fetch('http://site.api.espn.com/apis/site/v2/sports/' + sport + '/' + league + '/summary?event=' + id)
    .then(resp => resp.json())
    .then(json => {
      this.setState({game: json});
    });
  }
  
  colorBrightness(hex) {
    const result = brightnessRegex.exec(hex);
    return result ? (0.2126*parseInt(result[1], 16) + 0.7152*parseInt(result[2], 16) + 0.0722*parseInt(result[3], 16)) : null;
  }
  
  render() {
    const game = this.state.game;
    const {league, sport} = this.props;
      
    if (game) {
      const comp = game.header.competitions[0],
            awayTeam = comp.competitors.find(c => (c.homeAway === 'away')),
            homeTeam = comp.competitors.find(c => (c.homeAway === 'home')),
            status = comp.status.type.name,
            teamIds = [comp.competitors[0].team.id, comp.competitors[1].team.id];
            
      const boxscoreTeams = game.boxscore.teams;
      
      let stats = null;
      if (status === 'STATUS_INPROGRESS' || status === 'STATUS_FINAL') {
        stats = statDataSrc[league].map((src, idx) => {
          console.log('finding', src.name, boxscoreTeams);
          let label = null;
          const teams = boxscoreTeams.map(team => {
            const stat = team.statistics.find(stat => (stat.name === src.name));
            label = stat.label;
            return {
              color: team.team.color,
              abbreviation: team.team.abbreviation,
              chart: {value: stat.displayValue}
            }
          });
          
          console.log('make chart', src.type, src.label, teams);
          
          const ChartTag = (src.type === 'line') ? LineChart : PieChart;
          return (
            <li key={idx} className="stat-box">
  						<h3>{label}</h3>
  						<ChartTag teams={(src.type === 'line') ? teams : teams} />
  					</li>
          )
        })
      };
      
      const hasPicCenter = game.pickcenter.length,
            gameInfo = (<GameInfo
              gameInfo={game.gameInfo}
              overUnder={hasPicCenter ? game.pickcenter[0].overUnder : null}
              spread={hasPicCenter ? game.pickcenter[0].details : null}
              date={comp.date}
              broadcast={comp.broadcasts[0]}
              statusDetail={status}
      />);
      
      return (
        <Card raised={true} data-pagetype="gamepackage" id="game-card">
          <GameHeader comp={comp} league={league} gameNote={game.header.gameNote} statusDetail={status} />
          
          <div id="gamepackage-wrap">
	          <div id="gamepackage-content-wrap" className="layout-cbc">
              
              {status === 'STATUS_SCHEDULED' &&
                <Fragment>
                  <div className="col-one">
                    <MatchupPredictor competitors={comp.competitors} predictor={game.predictor} />
                  	{game.pickcenter.length ? <PickCenter pickCenter={game.pickcenter} awayTeam={awayTeam} homeTeam={homeTeam} /> : null}
                  </div>
                  
                  <div className="col-two" data-status={status} data-sport={sport}>
                    <LeaderCard awayId={awayTeam.id} leaders={game.leaders} league={league} sport={sport} teams={[comp.competitors[0], comp.competitors[1]]} />
                    <InjuryCard awayId={awayTeam.id} injuries={game.injuries} />
                    <TeamStatCard league={league} teams={game.boxscore.teams} />
                  </div>
                  
                  <div className="col-three">
                    <Standings group={game.standings.groups[0]} teamIds={teamIds} league={league} />
                    {(game.standings.groups.length > 1) && (<Standings group={game.standings.groups[1]} teamIds={teamIds} league={league} />)}
                    {gameInfo}
                  </div>
                </Fragment>
              }
              
              {(status === 'STATUS_FINAL') &&
                <Fragment>
                  <div className="col-one">
                    {
                      (sport === 'football') ?
                        <LeaderCard awayId={awayTeam.id} leaders={game.leaders} league={league} sport={sport} teams={[comp.competitors[0], comp.competitors[1]]} />
                      :
                        <GameLeaderTogglePanel
                          leaders={(game.leaders[0].team.id === awayTeam.id) ? game.leaders : game.leaders.reverse()}
                          teams={[comp.competitors[0], comp.competitors[1]]}
                        />
                    }
                    
                    <div id="gamepackage-team-stats-infographics">
                      <div className="sub-module team-statistics">
                        <header className="bordered">
                          <h1>Team Stats</h1>
                        </header>
                        <div className="content" id="graphs-wrap">
                          <div className="team-stats-wrap">
                            <ul className="stat-box-container">
                              {stats}
                            </ul>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div className="col-two" data-status={status} data-sport={sport}>
                    <Fragment>
                      <GameArticlePreview article={game.article} />
                      {(sport === 'football') ?
                        <FootballScoringSummary comp={comp} drives={game.drives.previous} scoringPlays={game.scoringPlays} />
                        : null
                      }
                    </Fragment>
                  </div>
                  
                  <div className="col-three">
                    {game.standings.groups.map((group, idx) => (<Standings key={idx} group={group} teamIds={teamIds} league={league} />))}
                    {gameInfo}
                  </div>
                </Fragment>
              }
          
            </div>
          </div>
        </Card>
      )
    }
    else {
      return null;
    }
  }
}