package es.uvigo.esei.daa.controller;

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

import java.util.List;

import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.PetDAO;

import es.uvigo.esei.daa.entities.Pet;

public class PetController {
	private final static Logger LOG = Logger.getLogger(PetController.class.getName());

	private PetDAO dao;

	public PetController() {
		this.dao = new PetDAO();
	}

	public PetDAO getDao() {
		return dao;
	}

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

	public Pet get(int id) {

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

		return pet;
	}

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

	public Pet add(String name, int owner, String surname) {
		Pet newPet;

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

		return newPet;
	}

	public void modify(Pet pet) {
		final Pet modifiedPet = new Pet(pet.getId(), pet.getName(), pet.getOwner(), pet.getType());

		try {
			this.dao.modify(modifiedPet);
		}

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

	}

	public void delete(int id) {

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

	}
}