package microfolie.service.transformer;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import microfolie.persistance.entity.Ecole;
import microfolie.persistance.entity.Usager;
import microfolie.persistance.entity.Ville;
import microfolie.persistance.table.EcoleTable;
import microfolie.persistance.table.VilleTable;
import microfolie.service.dto.UsagerDTO;

public class UsagerTransformer {
	
	private static VilleTable villeTable = VilleTable.getInstance();
	private static EcoleTable ecoleTable = EcoleTable.getInstance();
	
	public static Usager dtoToEntity(UsagerDTO dto) {
		Usager usager = new Usager();
		usager.prenom = dto.getPrenom();
		usager.nom = dto.getNom();
		usager.genre = dto.getGenre();
		usager.dateNaiss = dto.getDateNaissance();
		usager.email = dto.getEmail();
		usager.telephone = dto.getTelephone();
		usager.contactUrgence = dto.getContactUrgence();
		usager.code = dto.getCode();
		usager.description = "";
		// Cherche la ville correspondante au nom
		Optional<Ville> optVille = villeTable.findByLibelle(dto.getVille());
		if (optVille.isPresent()) {
			usager.ville = optVille.get();
		}
		// Situation
		if (!"aucun".equals(dto.getSituation().toLowerCase())) {
			usager.scolaire = true;
			Optional<Ecole> optEcole = ecoleTable.findByLibelle(dto.getSituation());
			if (optEcole.isPresent()) {
				usager.ecole = optEcole.get();
			}
		} else {
			usager.scolaire = false;
		}
		return usager;
	}
	
	public static List<Usager> dtoToEntity(List<UsagerDTO> dto) {
		List<Usager> result = new ArrayList<>();
		dto.forEach(elt -> result.add(dtoToEntity(elt)));
		return result;
	}
	
	public static UsagerDTO entityToDto(Usager usager) {
		UsagerDTO dto = new UsagerDTO();
		dto.setPrenom(usager.prenom);
		dto.setNom(usager.nom);
		dto.setGenre(usager.genre);
		dto.setDateNaissance(usager.dateNaiss);
		dto.setEmail(usager.email);
		dto.setTelephone(usager.telephone);
		dto.setContactUrgence(usager.contactUrgence);
		dto.setCode(usager.code);
		// Si il y a une ville
		if (usager.ville != null) {
			dto.setVille(usager.ville.libelle);
		}
		// Si il y a une ecole
		if (usager.scolaire && usager.ecole != null) {
			dto.setSituation(usager.ecole.libelle);
		} else {
			dto.setSituation("Aucun");
		}
		return dto;
	}
	
	public static List<UsagerDTO> entityToDto(List<Usager> usager) {
		List<UsagerDTO> result = new ArrayList<>();
		usager.forEach(elt -> result.add(entityToDto(elt)));
		return result;
	}

}
