package sklep.rest;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
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.Response;
import javax.ws.rs.core.Response.Status;

import sklep.db.CustomerDAO;
import sklep.db.DBConnection;
import sklep.db.DBException;
import sklep.db.RecordNotFound;
import sklep.model.Customer;

import javax.ws.rs.core.UriBuilder;

@Path("/customers")
@Produces({ "application/xml", "application/json", "text/plain"})
@Consumes({ "application/xml", "application/json" })
public class RCustomers {

	@POST
	public Response create(final Customer customer) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			customerDAO.insert(customer);
			db.commit();
			return Response.created(UriBuilder.fromResource(RCustomers.class).path(customer.getEmail()).build()).build();
		}
	}

	@GET
	@Path("/{email}")
	public Response findByEmail(@PathParam("email") final String email) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			Customer customer = customerDAO.findByEmail(email);
			return Response.ok(customer).build();
		} catch (RecordNotFound e) {
			return Response.status(Status.NOT_FOUND).build();
		}	
	}

	@GET
	public List<Customer> listAll() throws DBException {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			return customerDAO.readAll();
		}
	}

//	public List<Customer> listAll(@QueryParam("start") final Integer startPosition,
//			@QueryParam("max") final Integer maxResult) {}

	
	@PUT
	@Path("/{email}")
	public Response update(@PathParam("email") final String email, final Customer customer) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			customerDAO.update(customer);
			db.commit();
		}
		return Response.noContent().build();
	}

	@DELETE
	@Path("/{email}")
	public Response deleteById(@PathParam("email") final String email) throws DBException {
		try(DBConnection db = DBConnection.open()) {
			CustomerDAO customerDAO = db.customerDAO();
			customerDAO.delete(email);
			db.commit();
		}
		return Response.noContent().build();
	}

}
