/**
 * Game - Main JS file for game play, user, and file save.
 *
 * @date   2019-11-08
 * @author Rick Hays
 *
 */

let oUsers          = null;
let oCurrentUser    = null;
let userID          = null;
let userName        = '';
let userWins        = 0;
let userLoses       = 0;
let userLastPlayed  = '';
let userIP          = '';
let userCity        = '';
let userCountry     = '';

// Get current JSON file and import into array
$(document).ready(function ()
{
	$.getJSON('data/users.json', function (data)
	{
		// Pass data out so it can be used.
		getUsersData(data.Users);
		// Start of game screen, determine if there is a cookie or not and display correct screen
		userID = readCookie('userID');
		userID !== null ? $("#game").toggleClass('d-none') : $("#getuser").toggleClass('d-none');
	}, 'json');
});

function getUsersData(data)
{
	oUsers = data;
}

function writeUserData(data)
{

}

function submitUserName()
{
	UName = $("#UserName").val();
	if (UName === '')
	{
		$(".boxerror").html('You must enter a user name to play the game.');
		if ($(".boxerror").hasClass('d-none')) $(".boxerror").toggleClass('d-none');
	}
	else
	{
		$(".boxerror").toggleClass('d-none');
		userID = checkUserName(oUsers, UName);
//		alert('User ID: ' + userID);
		if (userID === null)
		{
			createUser(UName);
		}
		else
		{
			// Confirm User before loading else ask for new name

			// Load user info from userID
			userName = oUsers[userID].UserName;
			userWins = oUsers[userID].Wins;
			userLoses = oUsers[userID].Loses;
			userLastPlayed = oUsers[userID].LastDate;
			userIP          = oIP.ip;
			userCity        = oIP.city;
			userCountry     = oIP.country_code;

			alert('User: ' + userName + ' - City: ' + userCity);
			// userIP =  GET IP ADDRESS
			// create cookie with userID
		}
	}
}

function checkUserName(oUsers, name)
{
	for (let i = 0; i < oUsers.length; i++ )
	{
		if (oUsers[i].UserName === name)
			return i;
	}
	return null;
}

/**
 *
 * @param UName
 * @returns {boolean}
 */

function createUser(UName)
{
	userName        = UName;
	userWins        = 0;
	userLoses       = 0;
	userLastPlayed  = getCurrentDate();
	userIP          = oIP.ip;
	userCity        = oIP.city;
	userCountry     = oIP.country_code;

	// Create User Object
	oCurrentUser =
	{
		'UserName': userName,
		"Wins": userWins,
		"Loses": userLoses,
		"LastDate": userLastPlayed,
		"IP": userIP,
		"City": userCity,
		"Country": userCountry
	};
	// Add to Users Object
	oUsers.push(oCurrentUser);

	// Get ID of JSON User Position
	userID = checkUserName(oUsers, UName);

	// Write JSON file back out.

	// create cookie with userID
	alert('ID: ' + userID + ' - City: ' + oCurrentUser.City + ' - ' + oUsers[2].City);
}

function updateUser(UName)
{
}