/* eslint no-param-reassign: 0 */
import React, { Component, Fragment } from 'react';

import EnhancedTable from './enhanced-table.jsx';

const statCts = {
  passing: [1, 7, 0, 14, 13, 17, 4, 9, 3, 11, 12, 21],
  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
}

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) => {
    const retVal = !statsUsed.includes(stat.name);
    statsUsed.push(stat.name);
    return retVal;
  })
}

const getRowData = (catName, cats, catIdx, statIdx=0, totalOffset=0, getWholeStat=false) => {
  let rowData = {};
  const mapGuide = statCts[catName];
  console.log('getrowdata', getWholeStat, catName, catIdx, statIdx, cats);
  if (typeof mapGuide === 'number') {
    const stats = cats[catIdx].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 {
    for (let item of mapGuide) {
      //console.log('getstats', 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 class Demo extends Component {
  constructor(props) {
    super();
    this.state = {
      teamPlayerData: null,
      catIdx: 3
    };
    console.log('constructed');
  }
  
  componentDidMount() {
    console.log('mounted');
    fetch('https://site.web.api.espn.com/apis/site/v2/sports/football/nfl/teams/tb/athletes/statistics')
    .then(resp => resp.json())
    .then(json => {
      this.setState({teamPlayerData: json})
    });
    console.log('doc', document)
  }


  render() {
    const {
      teamPlayerData, catIdx
    } = this.state;
    
    if (teamPlayerData){
      const statCat = teamPlayerData.results[catIdx];
      
      const initLeaderStats = statCat.leaders[0].statistics;
      const initStatIdx = findStatIdx(initLeaderStats, 'name', statCat.name);
      
      let headCells = [];
      try {
        
        const initStats = getStatsWithoutDupes(initLeaderStats[0].stats);
        
        headCells.push({ id: 'playerName', numeric: false, label: 'Name', title: '' });
        headCells.push({ id: 'gamesPlayed', numeric: true, label: 'GP', title: 'Games Played' });
        
        console.log('getting hrd')
        const headRowData = getRowData(statCat.name, initLeaderStats, catIdx, 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);
        const leaderGeneralStats = findStat(leaderCats, 'name', 'general').stats;
        const statIdx = findStatIdx(leaderCats, 'name', statCat.name);
        
        console.log('grd main')
        
        const ns = leader.athlete.displayName.split(' ');
        const name = ns.shift()[0] + '. ' + ns.join(' ')

        
        let rowData = {
          playerName: (
            <React.Fragment>
              <span className="AnchorLink">{name}&nbsp;</span>
              <span className="n10 clr-gray-04">&nbsp;{leader.athlete.position.abbreviation}</span>
            </React.Fragment>
          ),
          gamesPlayed: leaderGeneralStats[leaderGeneralStats.length-1].value,
          ...getRowData(statCat.name, leaderCats, catIdx, statIdx)
        };
        
        rows.push(rowData);
      }
      
      const teamTotals = teamPlayerData.teamTotals;
      
      const totalStatIdx = findStatIdx(teamTotals, 'name', statCat.name);
      teamTotals[totalStatIdx].stats = getStatsWithoutDupes(teamTotals[totalStatIdx].stats);
      
      const generalStats = findStat(teamTotals, 'name', 'general').stats;
      console.log('grd foot', totalStatIdx, teamTotals);
      const footRow = {
          playerName: (<b>Total</b>),
          gamesPlayed: generalStats[generalStats.length-1].value,
          ...getRowData(statCat.name, teamTotals, 0, 0, totalStatIdx) };
        
      console.log('test', headCells, footRow);
      //rows.push(rowData);
      
      let colGroups = null;
      if (statCat.name === '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 (
        <EnhancedTable
          headCells={headCells}
          colGroups={colGroups}
          rows={rows}
          footRow={footRow}
          title={statCat.displayName}
        />
      );
    }
    else{
      return null;
    }
  }
};

export default Demo;