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

const getRosterContracts = (athletes, team, contractTeam) => {
  console.log('getroster contracts', team, athletes, contractTeam)
	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;
				for (let item of list.children) {
					const id = item.children[0].href.split('/')[7],
    					  h3 = item.querySelector('h3'),
    						injuryStatus = h3.nextElementSibling.lastElementChild.textContent,
    						noteEl = h3.nextElementSibling.nextElementSibling;
					if (injuryStatus.includes('reserve') || injuryStatus.includes('inactive') || noteEl && noteEl.textContent.includes('reserve')) {
						//console.log(date, item.children[0].href.split('/')[7], h3.childNodes[0].nodeValue, h3.nextElementSibling.lastElementChild.textContent);
						console.log('headshot', h3.childNodes[0].nodeValue, item.querySelector('img').getAttribute('src'), item.querySelector('img'))
						injuries.push({
							injured: true,
							id: id,
							fullName: h3.childNodes[0].nodeValue,
							injuryDate: date,
							injuryStatus: injuryStatus,
							headshot: {href: 'https://a.espncdn.com/combiner/i?img=/i/headshots/' + league + '/players/full/' + id + '.png&w=96'},
							position: {abbreviation: h3.firstElementChild.textContent}
						});
					}
				}
			}
			
			if (athletes[0].position.hasOwnProperty('id'))
			  athletes = [{items: athletes}];
			athletes.push({type: 'injuries', items: injuries});

			//let contractTeam = contracts[team.slug];
			//console.log('slug', team.slug)
			
			let unmatchNames = [],
				unmatchData = [],
				cUnmatches = Object.keys(contractTeam);
			//console.log('init cnames', cUnmatches)
			let matches = [];
			
			console.log('acheck', athletes.length, athletes);
			for (let teamType of athletes) {
				console.log('looping', teamType.position, teamType.items)
				for (let athlete of teamType.items) {
				  console.log('loop2', athlete);
					let aName = athlete.fullName.replace(dotRegex, '');
					if (contractTeam.hasOwnProperty(aName)) {
						newContracts[aName] = contractTeam[aName];
						if (cUnmatches.indexOf(aName) !== -1) {
							cUnmatches.splice(cUnmatches.indexOf(aName), 1);
							//console.log('removed', athlete.id, aName);
							athlete.contract = contractTeam[aName];
							matches.push(athlete);

							let unmatchIdx = unmatchNames.indexOf(aName);
							if (unmatchIdx !== -1) {
								//console.log('remove unmatch', aName);
								unmatchNames.splice(unmatchIdx, 1);
								unmatchData.splice(unmatchIdx, 1);
							}
						} else {
							//console.log('no match', athlete.id, aName)
						}
					} else {
						if (matches.indexOf(aName) === -1) {
							unmatchNames.push(aName);
							unmatchData.push(athlete);
							//console.log('nomatch', aName, matches)
						}
					}
				}
			}
			console.log('between1')

			for (let ui = 0; ui < unmatchNames.length; ++ui) {
				const unmatch = unmatchData[ui],
					hasFirstLast = unmatch.hasOwnProperty('firstName'),
					nameSplit = !hasFirstLast ? unmatch.fullName.split(' ') : null,
					firstName = hasFirstLast ? unmatch.firstName.replace(dotRegex, '') : nameSplit[0].replace(dotRegex, ''),
					lastName = hasFirstLast ? unmatch.lastName : nameSplit.slice(1).join(' '),
					aName = firstName + ' ' + lastName.split(' ')[0];

				if (contractTeam.hasOwnProperty(aName)) {
				  unmatch.contract = contractTeam[aName];
					matches.push(unmatch);
					cUnmatches.splice(cUnmatches.indexOf(aName), 1);
					unmatchNames.splice(ui, 1);
					unmatchData.splice(ui, 1);
					--ui;
				}
			}
			console.log('between2')

			for (let ui = 0; ui < unmatchNames.length; ++ui) {
				const unmatch = unmatchData[ui],
					hasFirstLast = unmatch.hasOwnProperty('firstName'),
					nameSplit = !hasFirstLast ? unmatch.fullName.split(' ') : null,
					firstName = hasFirstLast ? unmatch.firstName.replace(dotRegex, '') : nameSplit[0].replace(dotRegex, ''),
					lastName = hasFirstLast ? unmatch.lastName.split(' ')[0] : nameSplit.slice(1, 1);

				for (let ci = 0; ci < cUnmatches.length; ++ci) {
					const ns = cUnmatches[ci].split(' ');
					console.log('check', lastName, ns[1], firstName, ns[0])
					if (lastName === ns[1] && (firstName.includes(ns[0]) || ns[0].includes(firstName))) {
					  unmatch.contract = contractTeam[cUnmatches[ci]];
						matches.push(unmatch);
						cUnmatches.splice(ci, 1);
						unmatchNames.splice(ui, 1);
						unmatchData.splice(ui, 1);
						--ui;
						break;
					}
				}
			}

			console.log(matches.map((item) => item.fullName));
			console.log(unmatchNames);
			console.log(cUnmatches);
			console.log(team.slug);
			return matches;
		});
};



const sportPositions = {
  football: {
    offense: ['QB', 'RB', 'WR', 'TE', 'G', 'OT'],
    defense: ['DE', 'DT', 'LB', 'CB', 'S'],
    specialTeam: ['PK', 'P', 'LS']
  },
  basketball: ['PG', 'SG', 'SF', 'PF', 'C'],
  baseball: {
    'Pitchers': ['SP', 'RP'],
    'Catchers': ['C'],
    'Infielders': ['1B', '2B', '3B', 'SS'],
    'Outfielders': ['LF', 'CF', 'RF'],
    'Designated Hitters': [],
  }
};

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

const sortAthletes = (a, b) => {
  const aName = a.lastName + a.firstName,
        bName = b.lastName + b.firstName;
  return (aName < bName) ? -1 : (aName > bName) ? 1 : 0;
};

const sortPositions = (map, pos) => {
  map[pos] = [];
  return map;
}

export default class TeamRosterTable 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);
  }
  
  refresh() {
    console.log('roster panel mounted', this.props);
    if (this.props.data) {
      if (this.props.contracts) {
        this.getContracts();
      }
      else {
        this.getRoster();
      }
    }
  }
  
  componentDidMount() {
    this.refresh();
  }
  
  componentDidUpdate(prevProps) {
    if (prevProps.catIdx !== this.props.catIdx) {
      this.refresh();
    }
  }
  
  getRoster() {
    const {data, catIdx} = this.props;
    const sport = this.props.team.sport;
    
    const headCells = [
        { id: 'headshot', label: '', title: '' },
        { id: 'name', label: 'NAME', title: '' },
        { id: 'pos', label: 'POS', title: '' },
        { id: 'age', label: 'AGE', title: '' },
        { id: 'ht', label: 'HT', title: '' },
        { id: 'wt', label: 'WT', title: '' },
        { id: 'exp', label: 'EXP', title: '' },
        { id: 'college', label: 'COLLEGE', title: '' }
      ];
      
      const hasCat = !data.athletes[0].position.hasOwnProperty('id');
      let athletes = !hasCat ? data.athletes : data.athletes[catIdx].items;
      
      const sortedSport = sportPositions[sport];
      let sortedAthletes, sortedPositions;
      
      console.log('team roster parse', catIdx, sport, sortedSport, data);
      
      if (hasCat)
        sortedPositions = sortedSport[data.athletes[catIdx].position].reduce(sortPositions, {});
      else
        sortedPositions = sortedSport.reduce(sortPositions, {});
      
      for (let athlete of athletes) {
        sortedPositions[athlete.position.abbreviation].push(athlete);
      }
      
      sortedAthletes = [].concat.apply([], Object.values(sortedPositions));
      
      console.log('sortedP', sortedPositions);
      console.log('sortedA', sortedAthletes);
      
      const rows = sortedAthletes.map((athlete) => ({
        headshot: (<img alt={athlete.fullName} src={athlete.hasOwnProperty('headshot') ? athlete.headshot.href : 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'} height="56" />),
        name: (<Fragment>
          <span className="AnchorLink" onClick={this.callFetchPlayer} id={athlete.id}>{athlete.fullName}</span>
          <span className="pl2 n10">{athlete.jersey}</span>
        </Fragment>),
        pos: athlete.position.abbreviation,
        age: athlete.age,
        ht: athlete.displayHeight,
        wt: athlete.displayWeight,
        exp: athlete.experience.years + ' years',
        college: athlete.hasOwnProperty('college') ? athlete.college.name : ' '
      }));

      this.setState({
        headCells,
        rows
      });
  }
  
  
  
  getContracts() {
    const {data, catIdx, team, contracts} = this.props;
    console.log('team contracts parse', catIdx, data, contracts);
    
    const headCells = [
        { id: 'headshot', label: '', title: '' },
        { id: 'name', label: 'NAME', title: '' },
        { id: 'pos', label: 'POS', title: '' },
        { id: 'age', label: 'AGE', title: '' },
        { id: 'exp', label: 'EXP', title: '' },
        { id: 'terms', label: 'CONTRACTS TERMS', title: '' },
        { id: 'avgSalary', label: 'AVG SALARY', title: '' },
        { id: 'guaranteed', label: 'GUARANTEED', title: '' },
        { id: 'expires', label: 'EXPIRES', title: '' },
        { id: 'acquired', label: 'ACQUIRED', title: '' }
      ];
      
      const commaRegex = /,/g;
      getRosterContracts(data.athletes, team, contracts)
      .then((cAthletes) => {
        const sortedAthletes = cAthletes.sort((a, b) => {
          const aterm = a.contract[0],
                av = a.hasOwnProperty('contract') ? parseInt(aterm.substr(aterm.indexOf('$')+1).replace(commaRegex, '')) : 0,
                bterm = b.contract[0],
                bv = b.hasOwnProperty('contract') ? parseInt(bterm.substr(bterm.indexOf('$')+1).replace(commaRegex, '')) : 0;
          return bv - av;
        });
        
        console.log('sortedA', sortedAthletes);
        
        const rows = sortedAthletes.map((athlete) => {
          const contract = contracts[athlete.fullName],
                hasContract = !!contract;
          return {
            headshot: (<img alt={athlete.fullName} src={athlete.hasOwnProperty('headshot') ? athlete.headshot.href : 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'} height="56" />),
            name: (<Fragment>
              <span className="AnchorLink" onClick={this.callFetchPlayer} id={athlete.id}>{athlete.fullName}</span>
              <span className="pl2 n10">{athlete.jersey}</span>
            </Fragment>),
            pos: athlete.position.abbreviation,
            age: athlete.age,
            exp: athlete.hasOwnProperty('experience') ? athlete.experience.years + ' years': ' ',
            terms: hasContract ? contract[0] : ' ',
            avgSalary: hasContract ? contract[1] : ' ',
            guaranteed: hasContract ? contract[2] : ' ',
            expires: hasContract ? contract[3] : ' ',
            acquired: hasContract ? contract[4] : ' ',
          }
        });
  
        this.setState({headCells, rows});
        this.props.onload();
      });
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 
  
  render() {
    return this.state.rows ? (
      <EnhancedTable
        headCells={this.state.headCells}
        rows={this.state.rows}
        align="left"
      />
    ) : null;
  }
}