import React, { Component, Fragment } from 'react';
import EnhancedTable from './enhanced-table.jsx';

const eventShort = {
  'Wild Card': 'WC',
  'Divisional Round': 'DIV',
  'Conference Championship': 'CONF',
  'Super Bowl': 'SB'
};

const leadStats = {
  mlb: [
    {id: 'lead1', label: 'WIN P', title: 'Winning Pitcher'},
    {id: 'lead2', label: 'LOSS P', title: 'Losing Pitcher'},
    {id: 'lead3', label: 'SAVE P', title: 'Saving Pitcher'}
  ],
  nba: [
    {id: 'lead1', label: 'LEAD POINTS', title: 'Lead Scorer'},
    {id: 'lead2', label: 'LEAD ASSISTS', title: 'Lead Assister'},
    {id: 'lead3', label: 'LEAD REBOUNDS', title: 'Lead Rebounder'}
  ],
  nfl: [
    {id: 'lead1', label: 'LEAD PASS', title: 'Lead Passer'},
    {id: 'lead2', label: 'LEAD RUSH', title: 'Lead Rusher'},
    {id: 'lead3', label: 'LEAD REC', title: 'Lead Receiver'}
  ]
}

const shortDateOpts = {weekday: 'short', month: 'short', day: 'numeric'};

export default class TeamScheduleTable extends Component {
  constructor() {
    super();
    this.callShowTeam = this.callShowTeam.bind(this);
    this.callShowGame = this.callShowGame.bind(this);
    this.callFetchPlayer = this.callFetchPlayer.bind(this);
  }
  
  parseTeamSchedule() {
    const data = this.props.data,
          league = this.props.league;
    
    if (data) {
      console.log('team schedule parse', league, data)
      const teamAbbr = data.team.abbreviation;
      
      const leadStatLabels = leadStats[league];
      
      const headCells = [
        { id: 'date', label: 'DATE', title: '' },
        { id: 'opp', label: 'OPPONENT', title: '' },
        { id: 'result', label: 'RESULT', title: '' },
        { id: 'winloss', label: 'W-L', title: '' },
        leadStatLabels[0],
        leadStatLabels[1],
        leadStatLabels[2]
      ]
      
      if (league === 'nfl') {
        headCells.unshift({ id: 'week', label: 'WK', title: '' });
      }

      let lastWeekNum, hasFutureGames = false;
      const rows = [],
            futureRows = [];
            
      for (let ev of data.events) {
        const week = ev.week,
              rowData = {};
        
        if (league === 'nfl' && lastWeekNum < week.number-1) {
          rows.push({ week: week.number-1, date: (<b>BYE WEEK</b>), opp: ' ', result: ' ', winloss: ' ', lead1: ' ', lead2: ' ', lead3: ' ' });
        }
        
        
        const comp = ev.competitions[0],
              gameState = comp.status.type.state,
              ref = (comp.competitors[0].team.abbreviation === teamAbbr) ? comp.competitors[0] : comp.competitors[1],
              oppRef = (comp.competitors[0].team.abbreviation === teamAbbr) ? comp.competitors[1] : comp.competitors[0],
              oppTeam = oppRef.team,
              date = new Date(ev.date);
              
              
        if (league === 'nfl') {
          if (week.text.substr(0, 4) === 'Week')
            rowData.week = week.number;
          else if (week.text.includes('Preseason Week'))
            rowData.week = week.number-1;
          else
            rowData.week = eventShort[week.text];
          lastWeekNum = week.number;
        }
        
        rowData.date = date.toLocaleDateString("en-US", shortDateOpts);
        
        const vsAt = (ref.homeAway === 'home') ? 'vs' : '@';
        const oppLogoSrc = 'https://a.espncdn.com/combiner/i?img=/i/teamlogos/' + this.props.league + '/500/' + oppTeam.abbreviation + '.png&w=250&h=250';
        rowData.opp = (<span>{vsAt} <span className="AnchorLink pr2" data-id={oppTeam.id} onClick={this.callShowTeam}><img src={oppLogoSrc} alt={oppTeam.displayName} title={oppTeam.displayName} width="24" style={{verticalAlign: 'middle', marginRight: 6}} />{oppTeam.shortDisplayName}</span></span>);
        
        
        if (gameState === 'pre') {
          if (!hasFutureGames) {
            hasFutureGames = true;
            
            const subHeadRowData = {};
            
            if (league === 'nfl') {
              subHeadRowData.week = (<b>WK</b>);
            }
            
            subHeadRowData.date = (<b>DATE</b>);
            subHeadRowData.opp =(<b>OPPONENT</b>);
              //result: (<b>Opp W-L</b>),
              //winloss: (<b>W-L</b>),
            subHeadRowData.result = (<b>TIME</b>);
            subHeadRowData.winloss = (<b>TV</b>);
            subHeadRowData.lead1 = ' ';
            subHeadRowData.lead2 = ' ';
            subHeadRowData.lead3 = ' ';
            
            rows.push(subHeadRowData);
          }
          
          rowData.result = ' ';
          rowData.winloss = ' ';
          rowData.lead1 = ' ';
          rowData.lead2 = ' ';
          rowData.lead3 = ' ';
          
          //rowData.result = oppRef.record[0].displayValue;
          rowData.result = (<span className="AnchorLink pr2" onClick={this.callShowGame} id={ev.id}>{date.toLocaleString('en-US', {hour: 'numeric', minute: 'numeric', hour12: true })}</span>);
          for (let broadcast of comp.broadcasts) {
            if (broadcast.type.shortName === 'TV') {
              rowData.winloss = broadcast.media.shortName;
            }
          }
        }
        else if (gameState === 'post') {
          if (comp.status.type.name === 'STATUS_POSTPONED' || comp.status.type.name === 'STATUS_CANCELED') {
            rowData.result = (<b>{comp.status.type.shortDetail.toUpperCase()}</b>);
            rowData.winloss = ' ';
            rowData.lead1 = ' ';
            rowData.lead2 = ' ';
            rowData.lead3 = ' ';
          }
          else {
            const refLeaders = ref.leaders,
                  featuredAthletes = comp.status.featuredAthletes,
                  refScore = ref.score.value,
                  oppScore = oppRef.score.value,
                  isMLB = (league === 'mlb');
            
            const resultScore = ((vsAt === 'vs') ? refScore + '-' + oppScore : oppScore + '-' + refScore) + ' ' + (comp.status.type.altDetail || '');
            const refWon = (refScore > oppScore) ? 'W' : (oppScore > refScore) ? 'L' : 'T';
            rowData.result = (<Fragment>
              <span className={'fw-bold ' + ((refWon === 'W') ? 'clr-positive' : (refWon === 'L') ? 'clr-negative' : 'clr-gray-04' )}>{refWon}</span>
              <span className="AnchorLink ml3" onClick={this.callShowGame} id={ev.id}>{resultScore}</span>
            </Fragment>);
            rowData.winloss = ref.record.length ? ref.record[0].displayValue : ' ';
          
            console.log('leaders', refLeaders, featuredAthletes, ev);
            
            for (let i=1; i<=3; ++i) {
              rowData['lead' + i] = (isMLB && featuredAthletes[i-1]) ? (<Fragment>
                <span className="AnchorLink pr2" onClick={this.callFetchPlayer} id={featuredAthletes[i-1].athlete.id}>{featuredAthletes[i-1].athlete.lastName}</span>
                <span>{featuredAthletes[0].athlete.record}</span>
              </Fragment>) : (isMLB) ? null : (<Fragment>
                <span className="AnchorLink pr2" onClick={this.callFetchPlayer} id={refLeaders[i-1].leaders[0].athlete.id}>{refLeaders[i-1].leaders[0].athlete.shortName}</span>
                <span>{refLeaders[i-1].leaders[0].value}</span>
              </Fragment>);
            }
          }
        }
        
        rows.push(rowData);
      }
      console.log('schedule rows', rows);
      return {
        headCells,
        rows
      };
    }
    else{
      console.log('schedule no data');
      return null;
    }
  }
  
  callShowTeam(ev) {
    console.log('click', ev.currentTarget.dataset.id);
    const {sport, league} = this.props,
          team = this.props.teamData[sport][league][ev.currentTarget.dataset.id];
    team.sport = sport;
    team.league = league;
    this.props.showTeam(team);
  }
  
  callShowGame(ev) {
    console.log('click', ev.currentTarget.id);
    this.props.showGame(ev.currentTarget.id, this.props.sport, this.props.league);
    
  }
  
  callFetchPlayer(ev) {
    console.log('click', ev.target.id, ev.currentTarget);
    this.props.fetchPlayer(ev.target.id, this.props.sport, this.props.league);
  }
  
  render() {
    const data = this.parseTeamSchedule();
    
    return (
      <EnhancedTable
        headCells={data.headCells}
        rows={data.rows}
        align="center"
      />
    );
  }
}