const getRosterContracts = (athletes, team, contractTeam) => {
  console.log('getroster contracts', team, athletes, contractTeam)
	const newContracts = {},
		    dotRegex = /\./g;

	return fetch('https://devbydylan.com/sports/php/espn/injuries-scraper.php?league=nfl&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 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);
						injuries.push({
							injured: true,
							id: item.children[0].href.split('/')[7],
							fullName: h3.childNodes[0].nodeValue,
							injuryDate: date,
							injuryStatus: injuryStatus
						});
					}
				}
			}
			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) {
					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)
						}
					}
				}
			}

			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;
				}
			}

			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;
		});
};

module.exports = getRosterContracts;