/* global d3 */
var d3_players_data = [];

var POSITIONS = {
	0: 'CENTER',
	1: 'FORWARD',
	2: 'GUARD'
}

var POSITION_MAP = {
	"Center": "CENTER",
	"Center-Forward": "CENTER",
	"Center-Guard" : "CENTER",
	"Forward": "FORWARD",
	"Forward-Center": "FORWARD",
	"Forward-Guard": "FORWARD",
	"Guard" : "GUARD",
	"Guard-Forward": "GUARD",
	"Guard-Center" : "GUARD",
	"" : "GUARD"
}

/* takes a player json, and playerdata json and extracts the position */
function classifyPlayer(player, playerData) {
	var key = playerData.getPlayerKey(player);
	if (!playerData.hasData(key)) return "GUARD";
	
	return POSITION_MAP[playerData.getPlayerData(key)['position']];
}

function getTeamPositions(teams, playerData) {
	if (!teams || !playerData) {
		console.log("can't get team positions")
		return [];
	}
	
	var team_positions = [];
	for (var i = 0; i < 2; i++) {
		var team = teams[i];
		var positions = {'CENTER': [], 'FORWARD': [], 'GUARD': []};
		for (var playerKey in team) {
			var player = team[playerKey];
			
			var position = classifyPlayer(player, playerData);
			positions[position].push(player);	
		}
		team_positions.push(positions);
	}
	return team_positions;
}
var svg;
var width = 860;
var height = 400;

function initCourtVis() {
    console.log("initializing court vis");
    svg = d3.select("#court-vis").append("svg")
        .attr("viewBox", "0 0 " + width + " " + height)

    svg.append("image")
        .attr("id", "court-svg")
        .attr("preserveAspectRatio", "none")
        .attr("xlink:href", "../assets/img/fullcourt.svg");
        
    svg.append("svg:g")
        .attr("class", "players");

}

function formatPlayers(teams_by_positions, playerData, stat) {
	if (!teams_by_positions || !teams_by_positions[0] || !teams_by_positions[1]) return;
	var formattedPlayers = [];
	for (var i = 0; i < 2; i++) {
		var team = teams_by_positions[i];
		var totals = [team["CENTER"].length, team["FORWARD"].length, team["GUARD"].length]
		
		for (var position = 0; position < 3; position++) {
			var position_list = team[POSITIONS[position]];
			
			for (var player_index = 0; player_index < position_list.length; player_index++) {
				var player = position_list[player_index];
				
				player.position = position;
				player.player_index = player_index;
				player.position_total = totals[position];
				player.team = i;
				player.stat = playerData.getPlayerDatum(playerData.getPlayerKey(player), stat);
				formattedPlayers.push(player);
			}
		}
	}
	
	return formattedPlayers;
}

function calculateXPos(player) {
	if (player.team == 0) {
		return 120 * player.position;
	}
	else {
		return width - 120 * (player.position + 1);
	}
}

function calculateYPos(player) {
	var interval = height / (player.position_total + 1);
	return (player.player_index + 1) * interval;
}

function formatName(player) {
	return player.firstName.substr(0,1) + ". " + player.lastName;
}

function updateCourtVis(gameupdate, playerData, stat) {
	if (!gameupdate || !playerData) {
		console.log("leave")
		return;
	}
	var oncourt_players = gameupdate.getOnCourtPlayers();
	var teams_by_positions = getTeamPositions(oncourt_players, playerData);
	var formattedPlayers = formatPlayers(teams_by_positions, playerData, stat);
	
	if (!formattedPlayers) {
		console.log("leave")
		return;
	}
	var players = svg.selectAll(".player")
		.data(formattedPlayers)
		
	var stats = svg.selectAll(".stat")
		.data(formattedPlayers)
	
	players.enter()
		.append("text")
		
	stats.enter()
		.append("text")
	
	players
		.attr("class", "player")
		.attr("x", function(d) {return calculateXPos(d); })
        .attr("y", function(d) {return calculateYPos(d); })
        .text(function(d) {return formatName(d)});
    
    stats
    	.attr("class", "stat")
    	.attr("x", function(d) {return calculateXPos(d); })
        .attr("y", function(d) {return calculateYPos(d) + 20; })
        .text(function(d) {return d.stat});
        
    players.exit().remove();
    stats.exit().remove();
        
    
 
	
}