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

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

const noteRegex = new RegExp(',(?: \\w*){2,3} of.*');

const parseDate = (dateStr) => {
  const d1 = new Date(),
        d2 = new Date(dateStr),
        currentTime = d1.getTime();
  d1.setMonth(d2.getMonth());
  d1.setDate(d2.getDate());
  if (d1.getTime() > currentTime)
      d1.setYear(d1.getFullYear()-1);
  return d1.toISOString().slice(0, 10);
}

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

	return fetch('https://devbydylan.com/sports/php/espn/injuries-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('.layout__column--1 .ContentList');
			const injuries = [];

			for (let list of lists) {
				//console.log(list)
				const date = list.previousElementSibling.textContent;//,
				      //fullDate = parseDate(date);
				for (let item of list.children) {
					const h3 = item.querySelector('h3'),
    						injuryStatus = h3.nextElementSibling.lastElementChild.textContent,
    					  id = item.children[0].href.split('/')[7],
    					  noteEl = h3.nextElementSibling.nextElementSibling;
					//console.log(date, item.children[0].href.split('/')[7], h3.childNodes[0].nodeValue, h3.nextElementSibling.lastElementChild.textContent);
					//console.log('note', noteEl)
					injuries.push({
						id: id,
						position: h3.firstElementChild.textContent,
						fullName: h3.childNodes[0].nodeValue,
						headshotHref: 'https://a.espncdn.com/combiner/i?img=/i/headshots/' + league + '/players/full/' + id + '.png&w=96',
						date: date,
						status: injuryStatus,
						note: noteEl ? noteEl.textContent.replace(noteRegex, '') : ' '
					});
				}
			}

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



export default class TeamInjuryTable 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.getInjuries();
  }
  
  componentDidUpdate(prevProps) {
    if (prevProps.catIdx !== this.props.catIdx)
      this.getInjuries();
  }
  
  getInjuries() {
    const {catIdx, team} = this.props;
    console.log('team injury parse', catIdx);
    
    const headCells = [
      { id: 'position', label: 'POS', title: '' },
      { id: 'name', label: 'NAME', title: '' },
      { id: 'date', label: 'DATE', title: '' },
      { id: 'status', label: 'STATUS', title: '' },
      { id: 'notes', label: 'NOTE', title: '' }
    ];
      
    getInjuryData(team)
    .then((injuries) => {
      console.log('injuries', injuries);
      
      const rows = injuries.map((item) => {
        return {
          position: item.position,
          
          name: (<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>),
          date: item.date,
          status: item.status,
          note: (<div className="note">{item.note}</div>)
        };
        return rowData;
      });
      console.log('rows', rows);

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