import React, { Component, Fragment } from 'react';
import EnhancedTable from './enhanced-table.jsx';
//import getRosterContracts from '../utils/get-roster-contracts';

const depthLabels = ['starter', '2nd', '3rd', '4th'];

const sportsLeagues = {
  baseball: 'mlb',
  basketball: 'nba',
  football: 'nfl'
};

const getDepthChartData = (team) => {
  console.log('getroster contracts', team)
	const newContracts = {},
		    dotRegex = /\./g,
		    league = sportsLeagues[team.sport];

	return fetch('https://devbydylan.com/sports/php/espn/depth-chart-scraper.php?league=' + league + '&teamAbbr=' + team.abbreviation)
		.then(resp => resp.text())
		.then(html => {
			console.log('parsing', team.abbreviation);
			const parser = new DOMParser();
			const doc = parser.parseFromString(html, "text/html");
			const lists = doc.querySelectorAll('.ResponsiveTable');
			const depth = [];

			for (let list of lists) {
			  const tables = list.querySelectorAll('table');
				
				const posTableRows = tables[0].tBodies[0].children,
				      depthTableRows = tables[1].tBodies[0].children,
				      rowCt = posTableRows.length;
				for (let ri=0; ri<rowCt; ++ri) {
				
					const rowItem = {},
					      depthCols = depthTableRows[ri].children,
					      colCt = depthCols.length;
					      
					 console.log('check', depthTableRows[ri].textContent)
					      
					rowItem.position = posTableRows[ri].textContent.trim();
					      
					for (let ci=0; ci<colCt; ++ci) {
					  console.log('loop', depthCols[ci]);
					  const link = depthCols[ci].querySelector('a');
					  if (link) {
	            const id = link.href.split('/')[7];
  					  rowItem[depthLabels[ci]] = {
  							id: id,
  							fullName: link.textContent,
  							injuryStatus: link.nextElementSibling.textContent,
  							headshotHref: 'https://a.espncdn.com/combiner/i?img=/i/headshots/' + league + '/players/full/' + id + '.png&w=96'
  						};
					  }
					}
					depth.push(rowItem);
				}
			}

			console.log(depth);
			return depth;
		});
};



export default class TeamDepthTable extends Component {
  constructor(props) {
    super();
    this.state = {
      headCells: null,
      rows: null
    };
    this.callFetchPlayer = this.callFetchPlayer.bind(this);
  }
  
  callFetchPlayer(ev) {
    console.log('click', ev.target.id, ev.currentTarget);
    this.props.fetchPlayer(ev.target.id, this.props.team.sport, this.props.team.league);
  }
  
  componentDidMount() {
    this.getDepthChart();
  }
  
  componentDidUpdate(prevProps) {
    if (prevProps.catIdx !== this.props.catIdx)
      this.getDepthChart();
  }
  
  getDepthChart() {
    const {catIdx, team} = this.props;
    console.log('team depth parse', catIdx);
    
    const headCells = [
      { id: 'position', label: 'POS', title: '' },
      { id: 'starter', label: 'STARTER', title: '' },
      { id: '2nd', label: '2ND', title: '' },
      { id: '3rd', label: '3RD', title: '' },
      { id: '4th', label: '4TH', title: '' }
    ];
      
    getDepthChartData(team)
    .then((ufRows) => {
      console.log('ufRows', ufRows);
      
      const rows = ufRows.map((ufRow) => {
        const rowData = {};
        rowData.position = ufRow.position;
        for (let label of depthLabels) {
          const item = ufRow[label];
          rowData[label] = (item) ? (<Fragment>
            <img alt={item.fullName} src={item.headshotHref} className="depthchart-headshot" />
            <span className="AnchorLink" onClick={this.callFetchPlayer} id={item.id}>{item.fullName}</span>
            <span className="nfl-injuries-status ml3">{item.injuryStatus}</span>
          </Fragment>) : ' ';
        }
        return rowData;
      });
      console.log('rows', rows);

      this.setState({headCells, rows});
      this.props.onload();
    });
  }
  
 
  
  render() {
    return this.state.rows ? (
      <EnhancedTable
        headCells={this.state.headCells}
        rows={this.state.rows}
        align="left"
      />
    ) : null;
  }
}