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

const reactStringReplace = require('react-string-replace');
//import getRosterContracts from '../utils/get-roster-contracts';

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

/*const monthMap = {
  JAN: 'January', FEB: 'Febuary', MAR: 'March', APR: 'April', MAY: 'May', JUN: 'June', JUL: 'July', AUG: 'August', SEP: 'September', OCT: 'October', NOV: 'November', DEC: 'December'
};*/

const nameRegex1 = new RegExp('(?: |(?:, )|(?: and ))?([A-Z/]{1,4}(?:\/[A-Z]{1,3})?)((?: [A-Z][A-z.]+){1}(?: [a-z]+)?(?: [A-Z][A-z.]+){1,2}?)', 'g');
//cons nameRegex = new RegExp('(?: |(?:, )|(?: and ))?([A-Z]{1,4})((?: [A-Z][A-z.]+){1}(?: [a-z]+)?(?: [A-Z][A-z.]+){1,2}?)', 'g');
const nameRegex  = new RegExp("(?: |(?:, )|(?: and ))?([A-Z/]{1,4}(?:\/[A-Z]{1,3})?)((?: [A-Z][A-z.]+){1}(?: [a-z]+)?(?: [A-Z][A-z.]+){1,2}?)((?: (?!and)[A-Za-z0-9-/']+)*)", 'g');
                               

const sentenceRegex = new RegExp('(?<![. ][A-Z])\\.', 'g');
const actionRegex = /^(.+? )+?[A-Z][A-Z ]/;

const getTransactionData = (team, season) => {
  console.log('get transactions', team)
	const newContracts = {},
		    dotRegex = /\./g,
		    league = sportsLeagues[team.sport];

	return fetch('https://devbydylan.com/sports/php/espn/transactions-scraper.php?league=' + league + '&teamAbbr=' + team.abbreviation + '&season=' + season)
	.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 transactions = {};

		for (let list of lists) {
			
			const month = list.firstElementChild.textContent;
			//console.log(month, transactions[month])
			if (!transactions.hasOwnProperty(month))
			  transactions[month] = [];
			for (let row of list.querySelector('table').tBodies[0].children) {
			  //console.log('row', row)
				const dateStr = row.firstElementChild.textContent,
				      dateSplit = dateStr.split(' '),
				      date = dateSplit[0].substr(0, 3) + ' ' + dateSplit.slice(1).join(' '),
				      //notes = row.lastElementChild.textContent.split('. '),
				      notes = row.lastElementChild.textContent.split(sentenceRegex);
				notes.pop();
				    
				for (let note of notes) {
				  note = note.trim();
				  const transaction = note.replace(nameRegex1, '');
				  const actionMatch = note.match(actionRegex),
				        action = actionMatch ? actionMatch[1].trim() : '';
				  console.log('note', action, transaction, note);
				  
				  let lastDetail;
				  while (matches = nameRegex.exec(note)) {
            lastDetail = matches[3];
          }
				     
          let matches;
          while (matches = nameRegex.exec(note)) {
            transactions[month].push({
    					date: date,
    					name: matches[2].trim(),
    					position: matches[1],
    					transaction: matches[3] ? action + matches[3] : action + ' ' + lastDetail
    				});
          }
				}
				     
				//console.log(date, row.children[0].href.split('/')[7], h3.childNodes[0].nodeValue, h3.nextElementSibling.lastElementChild.textContent);
				//console.log('note', noteEl)
				
			}
		}

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



export default class TeamTransactionTable extends Component {
  constructor(props) {
    super();
    this.state = {
      headCells: null,
      rows: null
    };
    this.callFetchPlayer = this.callFetchPlayer.bind(this);
    this.getTransactions = this.getTransactions.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.state.month = this.props.month;
    this.state.season = this.props.season;
    console.log('transactions mount', this.props);
    this.getTransactions();
  }
  
  componentDidUpdate(prevProps) {
    console.log('trying to update', this.props.month, this.state.month, this.props.season, this.state.season);
    if (this.state.month !== this.props.month) {
      this.state.month = this.props.month;
      const rows = this.state.transactions[this.state.month].map((item) => ({
        date: item.date,
        name: item.name,
        position: item.position,
        transaction: reactStringReplace(item.transaction, nameRegex, (match) => (<b>{match}</b>))
      }));
      this.setState({rows: rows});
      this.props.onload();
    }
    else if (this.state.season !== this.props.season) {
      this.state.season = this.props.season;
      console.log('transactions update', this.props);
      this.getTransactions();
    }
  }
  
  getTransactions() {
    const {team, season} = this.props;
    console.log('team transaction parse', season, this.state.month, team);
    
    const headCells = [
      { id: 'date', label: 'DATE', title: '' },
      { id: 'name', label: 'Name', title: '' },
      { id: 'position', label: 'POS', title: '' },
      { id: 'transaction', label: 'TRANSACTION', title: '' }
    ];
      
    getTransactionData(team, season)
    .then((transactions) => {
      const months = Object.keys(transactions).map(month => ({value: month, displayValue: month}));
      
      if (!this.state.month)
        this.state.month = months[0].value
      const month = this.state.month;
      
      console.log('transactions', month, transactions);
      
		  this.props.setFilters({month: months}, {month: month, season: season});
      
      const rows = transactions[month].map((item) => ({
        date: item.date,
        name: item.name,
        position: item.position,
        transaction: reactStringReplace(item.transaction, nameRegex, (match) => (<b>{match}</b>))
      }));
      console.log('rows', rows);

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