package microfolie.service.transformer;

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

import microfolie.persistance.entity.Espace;
import microfolie.persistance.entity.Frequentation;
import microfolie.persistance.entity.Usager;
import microfolie.persistance.table.EspaceTable;
import microfolie.persistance.table.UsagerTable;
import microfolie.service.dto.FrequentationDTO;
import microfolie.utils.DateUtils;

public class FrequentationTransformer {
	
	private static UsagerTable usagerTable = UsagerTable.getInstance();
	private static EspaceTable espaceTable = EspaceTable.getInstance();
	
	public static Frequentation dtoToEntity(FrequentationDTO dto) {
		Frequentation freq = new Frequentation();
		freq.date = dto.getDate();
		Optional<Usager> optUsager = usagerTable.findByCode(dto.getUsagerCode());
		Optional<Espace> optEspace = espaceTable.findByCode(dto.getEspaceCode());
		if (optUsager.isPresent()) {
			freq.usager = optUsager.get();
		}
		if (optEspace.isPresent()) {
			freq.espace = optEspace.get();
		}
		return freq;
	}
	
	public static List<Frequentation> dtoToEntity(List<FrequentationDTO> dto) {
		List<Frequentation> result = new ArrayList<>();
		dto.forEach(elt -> result.add(dtoToEntity(elt)));
		return result;
	}
	
	public static FrequentationDTO entityToDto(Frequentation freq) {
		FrequentationDTO dto = new FrequentationDTO();
		dto.setDate(freq.date);
		if (freq.usager != null) {
			dto.setUsager(freq.usager.prenom + " " + freq.usager.nom);
			dto.setUsagerCode(freq.usager.code);
			dto.setAge(DateUtils.getAge(freq.usager.dateNaiss));
		}
		if (freq.espace != null) {
			dto.setEspace(freq.espace.libelle);
			dto.setEspaceCode(freq.espace.code);
		}
		return dto;
	}
	
	public static List<FrequentationDTO> entityToDto(List<Frequentation> freq) {
		List<FrequentationDTO> result = new ArrayList<>();
		freq.forEach(elt -> result.add(entityToDto(elt)));
		return result;
	}

}
