<!DOCTYPE html>
<html lang="es">
	<head>
		<meta charset="UTF-8">
		<title>Clinica Vida y Salud</title>
	</head>

	<body>
		<header>
			<div class="container">
				<h1 class="titulo">Clinica Vida y Salud</h1>
			</div>
		</header>	
		
		<main>
			<section class="container">
				<h2>Mis pacientes</h2>
				<table>
					<thead>
						<tr>
							<th>Nombre</th>
							<th>Peso(kg)</th>
							<th>Altura(m)</th>
							<th>Gordura Corporal(%)</th>
							<th>IMC</th>
						</tr>
					</thead>
					<tbody id="tabla-pacientes">
						
					</tbody>
				</table>
				
				<span id="error-ajax">Error al buscar los pacientes</span>

				<button id="buscar-paciente" class="boton bto-principal">
					Buscar Pacientes
				</button>

			</section>
		</main>


		<script>
			
	
						
			function adicionarPacienteEnLaTabla(paciente){
				var pacienteTr = construirTr(paciente);
				var tabla = document.querySelector("#tabla-pacientes");
				tabla.appendChild(pacienteTr);
			};
			
			
			function construirTr(paciente){
				var pacienteTr = document.createElement("tr");     
				pacienteTr.classList.add("paciente");
				pacienteTr.appendChild(construirTd(paciente.nombre,"info-nombre"));
				pacienteTr.appendChild(construirTd(paciente.peso,"info-peso"));
				pacienteTr.appendChild(construirTd(paciente.altura,"info-altura"));
				pacienteTr.appendChild(construirTd(paciente.gordura,"info-gordura"));
				pacienteTr.appendChild(construirTd(paciente.imc,"info-imc"));

				return pacienteTr; 
			};
			
			function construirTd(dato,clase){
				var td = document.createElement("td");
				td.classList.add(clase);
				td.textContent = dato;
				return td;
			}
			
			var errorAjax = document.querySelector("#error-ajax");
			errorAjax.style.visibility = "hidden";
			
			var botonBuscar = document.querySelector("#buscar-paciente");
			botonBuscar.addEventListener("click",function(){
				var xhr = new XMLHttpRequest;
				xhr.open("GET","https://alura-es-cursos.github.io/api-pacientes/pacientes.json");
				xhr.addEventListener("load",function(){
					
					if(xhr.status == 200){
						var respuesta = xhr.responseText;
						var pacientes = JSON.parse(respuesta);
						pacientes.forEach(function(paciente){
							adicionarPacienteEnLaTabla(paciente);
						});
					}else{
						errorAjax.style.visibility = "visible"
					}
				});  
				xhr.send();
			});
			
		</script>

	</body>

</html>