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

const statCts = {
  football: {
    passing: [1, 7, 0, 14, 13, 17, 4, 9, 3, 11, 12, 10],
    rushing: 10,
    receiving: [0, 1, 2, 12, 3, 4, 5, 6, 7, 8, 9, 10],
    defensive: [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 11], [0, 6], [1, 0], [1, 1], [0, 8], [1, 2], [2, 0], [2, 1], [2, 2], [0, 10]],
    scoring: 9
  },
  basketball: {
    general: [[0,3], [0,4], [0,6], [1,8], [1,9], [2,3], [0,0], [1,10], [2,2], [2,5], [1,11], [0,2], [0,1], [0,8]],
    scoring: [[1,22],[1,23],[1,15],[1,26],[1,27],[1,28],[1,24],[1,25],[1,0],[1,29],[1,30],[1,12],[1,13],[1,14]]
  },
  baseball: {
    batting: [16,1,7,2,8,9,4,3,10,11,12,5,6,13,14,15,19],
    pitching: [27,34,1,2,15,4,5,32,6,38,8,9,10,32,12,35,13,14],
    fielding: [10,11,1,2,3,4,7,5,6,8,12]
  }
};

const findStat = (arr, key, val) => arr.find(item => item[key] === val);
const findStatIdx = (arr, key, val) => arr.findIndex(item => item[key] === val);

const getStatsWithoutDupes = (stats) => {
  const statsUsed = [];
  return stats.filter((stat, idx, arr) => {
    //const retVal = !statsUsed.includes(stat.name);
    //statsUsed.push(stat.name);
    //return retVal;
    if (!statsUsed.includes(stat.name)) {
      
      statsUsed.push(stat.name);
      return true;
    }
    else {
      console.log('found dupe', idx, stat.name, arr);
    }
  });
};

const getRowData = (sport, catName, cats, catIdx, statIdx=0, totalOffset=0, getWholeStat=false) => {
  let rowData = {};
  const mapGuide = statCts[sport][catName];
  console.log('getrowdata', sport, catName, catIdx, statIdx, getWholeStat, cats, mapGuide);
  if (typeof mapGuide === 'number') {
    const stats = cats[statIdx].stats;
    for (let i=0; i<mapGuide; ++i) {
      const stat = stats[i];
      rowData[stat.name] = getWholeStat ? stat : stat.displayValue;//parseFloat(stat.displayValue.replace(',', ''));
    }
  }
  else if (typeof mapGuide[0] === 'object') {
    for (let item of mapGuide) {
      const stat = cats[item[0]+totalOffset].stats[item[1]];
      //console.log('mapguideitem', item, stat)
      rowData[stat.name] = getWholeStat ? stat : stat.displayValue;
    }
  }
  else {
    //console.log('getstats', catIdx, totalOffset, cats)
    for (let item of mapGuide) {
      //console.log('gettingstats', catIdx, totalOffset, item, cats[catIdx+totalOffset].stats[item])
      const stat = cats[catIdx+totalOffset].stats[item];
      rowData[stat.name] = getWholeStat ? stat : stat.displayValue;
    }
  }

  console.log('rowdataout', rowData);
  return rowData;
};




export default class TeamStatTable extends Component {
  constructor() {
    super();
    this.callFetchPlayer = this.callFetchPlayer.bind(this);
  }
  
  callFetchPlayer(ev) {
    console.log('click', ev.target, ev.currentTarget);
    this.props.fetchPlayer(ev.target.id, this.props.team.sport, this.props.team.league);
  }
  
  parseTeamStatData() {
    const {teamPlayerData, catName} = this.props;
    const sport = this.props.team.sport;
    const catIdx = (sport === 'basketball') ? 0 : this.props.catIdx;
            
    //console.log('looking for', catName, teamPlayerData.results);
    //const catIdx = teamPlayerData.results.findIndex(item => item.name === catName);
    //console.log('foundit', catIdx);
    if (teamPlayerData){
      const statCat = teamPlayerData.results[catIdx];
      
      const initLeaderCats = statCat.leaders[0].statistics;
      initLeaderCats[0].stats = getStatsWithoutDupes(initLeaderCats[0].stats);
      const initStatIdx = findStatIdx(initLeaderCats, 'name', catName);
      
      let headCells = [];
      try {
        headCells.push({ id: 'playerName', numeric: false, label: 'Name', title: '' });
        if (sport === 'football')
          headCells.push({ id: 'gamesPlayed', numeric: true, label: 'GP', title: 'Games Played' });
        
        //console.log('getting hrd');
        const headRowData = getRowData(sport, catName, initLeaderCats, 0, initStatIdx, 0, true);
        for (let key in headRowData) {
          const stat = headRowData[key];
          //console.log('hrd stat', key, stat);
          headCells.push({ id: key, numeric: true, label: stat.abbreviation, title: stat.displayName });
        }
      }
      catch(e) {
        console.error(e);
      }
      
      let rows = [];
      for (let leader of statCat.leaders) {
        const leaderCats = leader.statistics;
        leaderCats[0].stats = getStatsWithoutDupes(leaderCats[0].stats);
        let leaderGeneralStats;
        if (sport === 'football')
          leaderGeneralStats = findStat(leaderCats, 'name', 'general').stats;
        const statIdx = findStatIdx(leaderCats, 'name', catName);
        
        //console.log('grd main');
        
        const ns = leader.athlete.displayName.split(' ');
        const name = ns.shift()[0] + '. ' + ns.join(' ');
        
        let rowData = {
          playerName: (
            <Fragment>
              <span className="AnchorLink" onClick={this.callFetchPlayer} id={leader.athlete.id}>{name}&nbsp;</span>
              <span className="n10 clr-gray-04">&nbsp;{leader.athlete.position.abbreviation}</span>
            </Fragment>
          )
        };
        if (sport === 'football')
          rowData.gamesPlayed = leaderGeneralStats[leaderGeneralStats.length-1].value;
          
        rowData = {...rowData, ...getRowData(sport, catName, leaderCats, 0, statIdx)}
        console.log('tryrowdata', rowData);
        
        rows.push(rowData);
      }
      
      const teamTotals = teamPlayerData.teamTotals;
      
      const totalStatIdx = (sport === 'basketball') ? 0 : findStatIdx(teamTotals, 'name', catName);
      teamTotals[totalStatIdx].stats = getStatsWithoutDupes(teamTotals[totalStatIdx].stats);
      
      let generalStats;
        if (sport === 'football')
        generalStats = findStat(teamTotals, 'name', 'general').stats;
      //console.log('grd foot', totalStatIdx, teamTotals);
      let footRow = {
        playerName: 'Total'
      };
      if (sport === 'football')
        footRow.gamesPlayed = generalStats[generalStats.length-1].value;
        
      footRow = {...footRow, ...getRowData(sport, catName, teamTotals, 0, 0, totalStatIdx)};
        
      //console.log('test', headCells, footRow);
      //rows.push(rowData);
      
      let colGroups = null;
      if (sport === 'football' && catName === 'defensive') {
        colGroups = [
          {title: '', cols: new Array(2)},
          {title: 'TACKLES', cols: new Array(3)},
          {title: 'SACKS', cols: new Array(3)},
          {title: 'INTERCEPTIONS', cols: new Array(5)},
          {title: 'FUMBLES', cols: new Array(3)},
          {title: '', cols: new Array(1)}
        ];
      }
      
      return {
        headCells,
        colGroups,
        rows,
        footRow,
        title: statCat.displayName
      };
    }
    else{
      return null;
    }
  }
  
  render() {
    const data = this.parseTeamStatData();
    
    return (
      <EnhancedTable
        headCells={data.headCells}
        colGroups={data.colGroups}
        rows={data.rows}
        footRow={data.footRow}
      />
    );
  }
}