package es.uvigo.esei.daa.rest;

import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

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

@Path("/pet")
@Produces(MediaType.APPLICATION_JSON)
public class PetResource {

	private final PetController controller;

	public PetResource() {
		this(new PetController());
	}

	PetResource(PetController controller) {
		this.controller = controller;
	}

	/**
	 * Returns a pet with the provided identifier.
	 */
	@GET
	@Path("/{id}")
	public Response get(@PathParam("id") int id) {
		try {
			final Pet pet = this.controller.get(id);
			return Response.ok(pet).build();

		} catch (IllegalArgumentException iae) {

			return Response.status(Response.Status.BAD_REQUEST).entity(iae.getMessage()).build();

		} catch (RuntimeException e) {

			return Response.serverError().entity(e.getMessage()).build();
		}
	}

	@GET
	public Response list() {
		try {
			return Response.ok(this.controller.list()).build();

		} catch (RuntimeException e) {

			return Response.serverError().entity(e.getMessage()).build();
		}
	}

	/**
	 * Creates a new pet in the system.
	 */
	@POST
	public Response add(@FormParam("name") String name, @FormParam("owner") int owner, @FormParam("type") String type) {
		try {
			final Pet newPet = this.controller.add(name, owner, type);

			return Response.ok(newPet).build();

		} catch (IllegalArgumentException iae) {

			return Response.status(Response.Status.BAD_REQUEST).entity(iae.getMessage()).build();

		} catch (RuntimeException e) {

			return Response.serverError().entity(e.getMessage()).build();
		}
	}

	/**
	 * Modifies the data of a pet.
	 */
	@PUT
	@Path("/{id}")
	public Response modify(@PathParam("id") int id, @FormParam("name") String name, @FormParam("owner") int owner,
			@FormParam("type") String type) {
		try {
			final Pet modifiedPet = new Pet(id, name, owner, type);
			this.controller.modify(modifiedPet);

			return Response.ok(modifiedPet).build();

		} catch (IllegalArgumentException iae) {

			return Response.status(Response.Status.BAD_REQUEST).entity(iae.getMessage()).build();

		} catch (RuntimeException e) {

			return Response.serverError().entity(e.getMessage()).build();
		}
	}

	/**
	 * Deletes a pet from the system.
	 */
	@DELETE
	@Path("/{id}")
	public Response delete(@PathParam("id") int id) {
		try {
			this.controller.delete(id);

			return Response.ok(id).build();

		} catch (IllegalArgumentException iae) {

			return Response.status(Response.Status.BAD_REQUEST).entity(iae.getMessage()).build();

		} catch (RuntimeException e) {

			return Response.serverError().entity(e.getMessage()).build();
		}
	}

}