var table = document.getElementById("game-table");
var tableBody = table.getElementsByTagName('tbody')[0];
var tableRow = table.getElementsByTagName('tr')[0];
var tableFooter = table.getElementsByTagName('tfoot')[0];
var footerRow = tableFooter.getElementsByTagName('tr')[0];
//! todo , game mode validation before start
var idCounter = 1;
var name;
var goal;
var currentRoundScore = 0;
var totalScore = 0;
var leftToWin;

var roundCounter = 1;
var playerCounter = 1;


// Add new player to list
var playersList = document.getElementById("players-list");
function addPlayer() {
	var li = document.createElement("li");
	li.setAttribute('class', 'player');
	var playerValue = document.getElementById("add-player").value; //for reloaded or empty

	var playerIncrement = playerCounter++;
	var playerSpan = document.createElement("span");
	//playerSpan.innerHTML = "Player " + playerIncrement + ": ";
	var activePlayer = playerValue;

	li.append(activePlayer);
	if (playerValue === "") {
    	alert("No! Enter player name!");
	} else {
		playersList.appendChild(li);
	}
	document.getElementById("add-player").value = "";
	
	// Show modes if at least 1 player entered
	var modesWrapper = document.getElementById("modes");
	var startBtn = document.getElementById("start");
	var aP = document.querySelectorAll(".player").length;
	console.log(playersList.length);
	if (aP >= 1) {
		modesWrapper.style.display = "block";
		startBtn.style.display = "inline-block";
	} 
}
var input = document.getElementById("add-player");
input.addEventListener("keyup", function() {
  if (event.keyCode === 13) {
    addPlayer();
  }
}); 

// Modes list toggle
var modes = document.getElementById("modes-list");

function showModes() {
	if (modes.style.display === "none") {
    	modes.style.display = "block";
	} else {
		modes.style.display = "none";
	}
}

// Get mode, add li and replace value of select
var activeMode = document.getElementById("active-mode");
modes.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    var selectedMode = ev.target.innerHTML;
    var md = document.getElementById("select-mode");
    md.innerHTML = selectedMode;
    modes.style.display = "none";
    activeMode.innerHTML = selectedMode;
  }
}, false);


function startGame() {
	var activePlayers = document.querySelectorAll(".player");
	var playersArray = Array.prototype.slice.call(activePlayers);

	var goalStr = activeMode.innerHTML;
	goal = parseInt(goalStr);

	// Creating input to use for each round
	var roundInput = document.createElement("INPUT");
	roundInput.setAttribute("type", "number");
	roundInput.setAttribute("class", "player-score");

	// Check for players and game mode
	if (playersArray.length < 1) {
    	alert("No! Enter player name!");
	}
	// cannot get god damn isNaN to work, so its like this, via regex
	if (!/^\d+(\.\d+)?/.exec(goal)) {
		alert("No! Select game mode!");
	} else {
	    table.style.display = "table";
	    var entry = document.getElementsByClassName("entry");
	    //var entryArr = Array.prototype.slice.call(entry);
	    for (var i = 0; i < entry.length; i++) {
	    	entry[i].style.display = "none";
	    }

	    var playerScore;

		// inserting player names in cells
		var player = [];
		var newCell;
		for (var i = 0; i < playersArray.length; i++) {
			player[i] = {
				id: idCounter++,
		        name: name,
		        goal: goal,
		        currentRoundScore: currentRoundScore,
		        totalScore: totalScore,
		        leftToWin: leftToWin
		    };
		    var playerNames = playersArray[i].innerHTML;

		    player[i].name = playerNames;
		    console.log(playerNames);
		    player[i].leftToWin = player[i].goal;

		    var newCell  = tableRow.insertCell(-1);
			newCell.innerHTML = player[i].name;
		    var playerScore = goal;
		    var footerCell = footerRow.insertCell(-1);
		    footerCell.innerHTML = player[i].leftToWin;
		}

		var roundNext;

		function addRow() {
			var roundPlayers = playersArray.length;
			var roundRow = tableBody.insertRow(-1);
			var roundNumber = roundRow.insertCell(0);
			var roundNumberIndex = roundCounter++;
			roundNumber.innerHTML = roundNumberIndex;
			var roundNext = roundRow.insertCell(-1);

			// Next round 
			var roundNextBtn = document.createElement("BUTTON");   
			roundNextBtn.innerHTML = " + NEXT"; 
			roundNextBtn.onclick = function() {
				var thisRow = this.parentNode.parentNode;
				var playersScoresList = thisRow.getElementsByClassName("player-score");
				var playersScores = Array.prototype.slice.call(playersScoresList);

				// First check if values are entered like numbers
				for (var i = 0; i < playersScores.length; i++) {
					var check = parseInt(playersScores[i].value, 10);
					if (!/^\d+(\.\d+)?/.exec(check)) {
						alert("No! Player is missing this round value! If you missed or went overboard, HA-HA! (write 0)");
						return;
					} 
				}

				
				// Getting players round scores and calculating left to win
				for (var i = 0; i < playersScores.length; i++) {
					var score = parseInt(playersScores[i].value, 10);
					player[i].currentRoundScore = score;
					console.log(score);
					player[i].totalScore += player[i].currentRoundScore;
					player[i].leftToWin = goal - player[i].totalScore;
					console.log(player[i].totalScore);	

				};

				console.log(player);

				// Remove existing row and create new with updated values
				tableFooter.deleteRow(0);
				var tableRowUpdated = tableFooter.insertRow(0);
				var totalCell = tableRowUpdated.insertCell(0);
				totalCell.innerHTML = "=";

				// Getting players updated left to win and append in tfoot
				for (var i = 0; i < playersArray.length; i++) {
					var updatedLTW = player[i].leftToWin;
					console.log("Player: " + player[i].name + " has "  + updatedLTW + " to win");
					var footerCellUpdated = tableRowUpdated.insertCell(-1);
					footerCellUpdated.innerHTML = player[i].leftToWin;
				}

				//same as above
				//for (key in player) {
				//	if (player.hasOwnProperty(key)) {
				//	  	console.log(player[key].leftToWin);
				//		var footerCellUpdated = tableRowUpdated.insertCell(-1);
				//	  	footerCellUpdated.innerHTML = player[key].leftToWin;
				//	}
				//}

				// Disable this rounds inputs
				var inputs = thisRow.querySelectorAll("input");
				var inputsArr = Array.prototype.slice.call(inputs);
				console.log(inputsArr);
				for (var i = 0; i < inputsArr.length; i++) {
					inputsArr[i].setAttribute("disabled", "disabled")
				}

				// Are we done
				for (var i = 0; i < playersArray.length; i++) {
					if (player[i].leftToWin === 0) {
						var winner = player[i].name;
						var capitalWinner = winner.charAt(0).toUpperCase() + winner.substring(1);
						alert("GG " + capitalWinner);
						this.setAttribute("disabled", "disabled");
						return;
					} 
				}

				addRow();

				// Remove this Next button
				roundNext.removeChild(roundNext.childNodes[0]);

				
			};

			// New round Next button
			roundNextBtn.setAttribute("class", "next-round");
			roundNext.appendChild(roundNextBtn);

			// New round inputs
			for (var i = 0; i < playersArray.length; i++) {
				var newRoundCell  = roundRow.insertCell(1);
				newRoundCell.append(roundInput.cloneNode());
			}
		}

		// Starting game, first round row
		var firstRoundRow = addRow();

		// New game button, page refresh at this point
		var newGameBtn = document.createElement("BUTTON");
		var mainWrapper = document.getElementById("main-wrapper");
		mainWrapper.appendChild(newGameBtn);
		newGameBtn.setAttribute("class", "new-game btn");
		newGameBtn.innerHTML = "START NEW GAME";
		newGameBtn.onclick = function() {
			window.location.reload();
		}
	}

}