var active_timer = 100;
var eaters = []

$( function() {
	$(".user-result-container").position({
	    my:        "left top",
	    at:        "left bottom",
	    of:        $('#search-user'),
	    collision: "fit"
	});
	$('.user-result-container').hide();
    $( "#datepicker" ).datepicker({
    	dateFormat: 'D, yy-mm-dd'
    });
    $('#spinner-hour').spinner({
    	min: 0,
    	max: 23,
    	numberFormat: 'n'
    });
    $('#spinner-minute').spinner({
    	min: 0,
    	max: 59,
    	numberFormat: 'n'
    });
    $('#search-user').on('keyup', function(){
    	clearTimeout(active_timer);
    	active_timer = setTimeout(user_search, 500);
    });
    eaters.push($($('.username')[0]).text()); // Kinda weird but ok
});

function plan_meal() {

}

function add_user() {
	if (eaters.includes($('#search-user').val()))
		return;
	$.ajax({
		url: "/searchusers?q=" + $('#search-user').val() + "&s=0"
	}).done(function(results) {
		if (results == '[]') {
			alert('Invalid username');
			return;
		}
		var meal_date = $('#datepicker').datepicker('getDate');
		if (meal_date == null || $('#spinner-hour').val() == '' || $('#spinner-minute').val() == '') {
			alert('Please select a date and a time.');
			return;
		}
		names = results.substring(1, results.length - 1).split(', ');
		new_eater = names[0].substring(1, names[0].length - 1);
		eaters.push(new_eater);
		var month = (meal_date.getMonth() + 1).toString();
		if (month.length == 1)
			month = '0' + month;
		var date = (meal_date.getDate()).toString();
		if (date.length == 1)
			date = '0' + date;
		if ($('#spinner-hour').val().length == 1)
			$('#spinner-hour').val('0' + $('#spinner-hour').val());
		if ($('#spinner-minute').val().length == 1)
			$('#spinner-minute').val('0' + $('#spinner-minute').val());
		var meal_timestamp = meal_date.getFullYear() + '-' +
							 month + '-' +
							 date + ' ' +
							 $('#spinner-hour').val() + ':' +
							 $('#spinner-minute').val();
		$.ajax({
			url: "/getkukcandidate?date=" + meal_timestamp + "&eaters=" + eaters.toString()
		}).done(function(estkuk) {
			$('#est-cook').attr('src', 'static/' + estkuk + '.png')
			$('#est-cook').attr('title', estkuk)
		});
		e = '<div class="add-people-container" id="for-user-' + new_eater + '">\
			<div class="flex-card" style="margin: 0">\
				<img src="static/' + new_eater + '.png" class="flex-thumb">\
				<span class="username">' + new_eater + '</span>\
			</div>\
			<div class="small-round-button" onclick="remove_user(\'' + new_eater + '\')"><i class="fa fa-minus" aria-hidden="true"></i></div>\
		</div>';
		$('#add-user').before(e);
		$('.small-round-button').show();
	});
}

function remove_user(name) {
	eaters = eaters.filter(function(value, index, arr){
	    return value != name;
	});
	$('#for-user-' + name).remove();
	if ($('#eaters-list > div').length == 2) {
		$('.small-round-button').hide();
	}
}

function fill_box(name) {
	$('#search-user').val(name);
	$('.user-result-container').hide();
}

function user_search() {
	$('.user-result-container').hide();
	if ($('#search-user').val() == '')
		return;
	$.ajax({
		url: "/searchusers?q=" + $('#search-user').val() + "&s=1"
	}).done(function(results) {
		// Load results
		if (results == '[]')
			return;
		$('.user-result-container').empty();
		names = results.substring(1, results.length-1).split(', ');
		$.each(names, function(i, r){
			var name = r.substring(1, r.length-1);
			e = '<div class="user-result" onclick="fill_box(\'' + name + '\')">\
			<img src="static/' + name + '.png" class="user-result-thumb">\
			<span class="username">' + name + '</span>\
			</div>'
			$('.user-result-container').append($(e));
		});
		// $(".user-result-container").position({
		//     my:        "left top",
		//     at:        "left bottom",
		//     of:        $('#search-user'),
		//     collision: "fit"
		// });
		$('.user-result-container').show();
	});
}