

//Funtions
function onSubmitAnimal(form){
	var data = {};
	$.map($(form).serializeArray(), function(n, i){
		if(n['value']!= "") data[n['name']] = n['value'];
		else data[n['name']] = null;
	});
	
	if(data._id){
		$.ajax({
			type: "PUT",
			url: "/animal/"+data._id,
			data: JSON.stringify(data),
			success: function() { showAnimal(data._id) },
			contentType : "application/json"
		});
	}else{
		$.ajax({
			type: "POST",
			url: "/animal",
			data: JSON.stringify(data),
			success: function() { $("#animals").click() },
			contentType : "application/json"
		});
	}
	return false;
};

function editAnimal(id){
	$("#load").fadeIn(0);
	$( "#body" ).load( "/templates/animal-form.html", function(){
		var animal;
		$.get( "/animal/"+id, function( data ) {
			animal = data.data
			for(key in animal)
			{
				if(animal.hasOwnProperty(key)){
					if(key == "father" || key == "mother" || key == "specie" || key == "sex"){
						let a = key;
						setTimeout(function(){
							$('#a-'+a+' option[value='+animal[a]+']').attr('selected','selected');
						}, 200)
					}else{
						$('input[name='+key+']').val( animal[key] ?animal[key].$numberDecimal ? animal[key].$numberDecimal : animal[key] : "");
					}
				}
			}
			set_animal_include(animal._id);
			paint_male_female(animal.specie, animal._id);
			$("#load").fadeOut("fast");
		});
	});
}

function showAnimal(id){
	$("#load").fadeIn(0);
	$( "#body" ).load( "/templates/animal-show.html", function(){
		var text = "<div><b>Stats</b></div><table class=\"dataTable\">";
		$.get( "/animal/"+ id, function( data ) {
			var animal = data.data,
				j = 1;
			$.each(animal, function(i, val) {
				if(i == "specie")
					text += "<tr><td>"+i+"</td><td>" + species[val].name + "</td></tr>";
				else if(i != "_id" && i != "__v" && i != "father" && i != "mother" && i != "name" && i.indexOf("initial") < 0 && i != "specie" && i != "level")
					text += "<tr><td>"+i+"</td><td>"+(val ? val.$numberDecimal ? val.$numberDecimal :  val : "")+"</td></tr>";
				j++;
			});
			text += "</table>";
			
			$("#button").html('<button class="btn btn-info btn-sm float-right" onclick="editAnimal(\''+ animal._id +'\')">Edit</button>')
			$(".a-name").html( "<span>" + animal.name + "</span><br>" + " Level: " + animal.level + " - " + species[animal.specie].name );
			$("#data").append( text );
			
			get_parrents(animal);
			get_childrens(animal);
			set_chart('myAnimalChar', animal);
			$("#load").fadeOut("fast");
		});
		
	});
}

function removeAnimal(id){
	if(confirm("¿Surely you want to erase this dino?")){
		$.ajax({
   			url: '/animal/'+id,
			type: 'DELETE',
			success: function() { $("#animals").click() }
		});
	}
}


function paint_male_female(specie, id){
	$(".option").remove();
	$.get( "/animal/"+specie+"/Male", function( data ) {
		data.data.map(function(item){
			if(item._id != id) $("#a-father").append("<option class=\"option\" value='"+item._id+"'>"+item.name+" - "+ item.level +"</option>");
		})
	});
	
	$.get( "/animal/"+specie+"/Female", function( data ) {
		data.data.map(function(item){
			if(item._id != id) $("#a-mother").append("<option class=\"option\" value='"+item._id+"'>"+item.name+" - "+ item.level +"</option>");
		})
	});
}

function get_parrents(animal){
	$.get( "/animal/parrents/" + animal._id, function( data ) {
		data.data.map(function(item){
			$(item.sex == "Male" ? "#a-father" : "#a-mother").html(paint_animal(item));
		});
	});
}

function get_childrens(animal){
	$.get( "/animal/childrens/" + animal._id, function( data ) {
		data.data.map(function(item){
			$("#a-childrens").append("<div class=\"col-6\">" + paint_animal(item) + "</div>");
		})
	});
}

function set_animal_include(id){
	$.get( "/species", function( data ) {
		data.data.map(function(item){
			$("#a-specie").append("<option value='"+item._id+"'>"+item.name+"</option>");
		});
	});
	$("#a-specie").change(function(e){
		paint_male_female($( this ).val(), id);
	});
}

function get_info(){
    $.get("/info", function( data ) {
        var text = "<table class=\"info\">"
        $.each(data, function(i, obj) {
            text += "<tr><td>"+i+"</td><td> "+obj+"</td></tr>";
        });
        text += "</table>"
		$( "#info" ).html( text );
		$("#load").fadeOut("slow");
    });
}

function paint_animal(a){
	console.log(a);
	return "<button onclick=\"showAnimal('"+ a._id +"')\">" + a.name+" - "+ a.level + "</button>"
		+ '<table class="dataTable">'
		+ '<tr><td>Uuid</td><td>' + safe(a.uuid) + '</td></tr>'
		+ '<tr><td>Breeder</td><td>' + safe(a.breeder) + '</td></tr>'
		+ '<tr><td>Health</td><td>' + safe(a.health) + '</td></tr>'
		+ '<tr><td>Stamina</td><td>' + safe(a.energy) + '</td></tr>'
		+ '<tr><td>Food</td><td>' + safe(a.food) + '</td></tr>'
		+ '<tr><td>Damage</td><td>' + safe(a.damage) + '</td></tr>'
		+ '<tr><td>Speed</td><td>' + safe(a.velocity) + '</td></tr>'
		+ '</tr>'
		+ '<table>'
		+ '</table>'
}

function safe(s){
	return s ? s.$numberDecimal ? s.$numberDecimal : s : ""
}