package es.uvigo.esei.daa.controller;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.PeopleDAO;
import es.uvigo.esei.daa.entities.Person;
import es.uvigo.esei.daa.entities.Pet;

public class PeopleController {
	private final static Logger LOG = Logger.getLogger(PeopleController.class.getName());
	private PeopleDAO dao;

	public PeopleController() {
		this.dao = new PeopleDAO();
	}

	public PeopleDAO getDao() {
		return dao;
	}

	public void setDao(PeopleDAO dao) {
		this.dao = dao;
	}

	public Person get(int id) {
		Person person;

		try {
			person = this.dao.get(id);
		} catch (IllegalArgumentException iae) {
			LOG.log(Level.FINE, "Invalid person id in get method", iae);
			throw new IllegalArgumentException(iae);
		} catch (DAOException e) {
			LOG.log(Level.SEVERE, "Error getting a person", e);
			throw new RuntimeException(e);
		}

		return person;
	}

	public List<Pet> pets(int ownerId) {
		List<Pet> petList;

		try {
			petList = this.dao.pets(ownerId);
		} catch (DAOException e) {
			LOG.log(Level.SEVERE, "Error getting pets", e);
			throw new RuntimeException(e);
		}

		return petList;
	}

	public List<Person> list() {
		List<Person> personList;
		try {
			personList = this.dao.list();
		} catch (DAOException e) {
			LOG.log(Level.SEVERE, "Error listing people", e);
			throw new RuntimeException(e);
		}
		return personList;
	}

	public Person add(String name, String surname) {
		Person newPerson;

		try {
			newPerson = this.dao.add(name, surname);
		} catch (IllegalArgumentException iae) {
			LOG.log(Level.FINE, "Invalid person id in add method", iae);
			throw new IllegalArgumentException(iae);
		} catch (DAOException e) {
			LOG.log(Level.SEVERE, "Error adding a person", e);
			throw new RuntimeException(e);
		}

		return newPerson;
	}

	public void modify(Person person) {
		final Person modifiedPerson = new Person(person.getId(), person.getName(), person.getSurname());

		try {
			this.dao.modify(modifiedPerson);
		} catch (NullPointerException e) {
			LOG.log(Level.FINE, "Invalid data for person", e);
			throw new IllegalArgumentException(e);
		} catch (IllegalArgumentException iae) {
			LOG.log(Level.FINE, "Invalid person id in modify method", iae);
			throw new IllegalArgumentException(iae);
		} catch (DAOException e) {
			LOG.log(Level.SEVERE, "Error modifying a person", e);
			throw new RuntimeException(e);
		}
	}

	public void delete(int id) {

		try {
			this.dao.delete(id);
		} catch (IllegalArgumentException iae) {
			LOG.log(Level.FINE, "Invalid person id in delete method", iae);
			throw new RuntimeException(iae);

		} catch (DAOException e) {
			LOG.log(Level.SEVERE, "Error deleting a person", e);
			throw new RuntimeException(e);
		}
	}
}
