package com.jax.security;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

import javax.annotation.security.RolesAllowed;
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.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/customers")
public class CustomerService 
{
	@RolesAllowed("ADMIN")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public Customers getCustomers() 
	{
		Customers list = new Customers();
		list.setCustomerList(new ArrayList<Customer>());
		
		list.getCustomerList().add(new Customer(1, "Customer 1"));
		list.getCustomerList().add(new Customer(2, "Customer 2"));
		list.getCustomerList().add(new Customer(3, "Customer 3"));
		list.getCustomerList().add(new Customer(4, "Customer 4"));
		
		return list;
	}
	
	@RolesAllowed("ADMIN")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response addCustomer(Customer customer) throws URISyntaxException 
	{
		if(customer == null){
			return Response.status(400).entity("add customer").build();
		}
		
		if(customer.getName() == null) {
			return Response.status(400).entity("provide customer name").build();
		}
		
		return Response.created(new URI("/rest/customers/"+customer.getId())).build();
	}
	
	@GET
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateCustomerById(@PathParam("id") Integer id) 
	{
		if(id  < 0){
			return Response.noContent().build();
		}
		Customer customer = new Customer();
		
		customer.setId(id);
		customer.setName("Customer modified");
		
		GenericEntity<Customer> entity = new GenericEntity<Customer>(customer, Customer.class);
		return Response.ok().entity(entity).build();
	}
	
	@PUT
	@Path("/{id}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateCustomerById(@PathParam("id") Integer id, Customer customer) 
	{
		Customer updatedCustomer = new Customer();
		
		if(customer.getName() == null) {
			return Response.status(400).entity("provide customer name").build();
		}
		
		updatedCustomer.setId(id);
		updatedCustomer.setName(customer.getName());
		
		return Response.ok().entity(updatedCustomer).build();
	}
	
	@DELETE
	@Path("/{id}")
	public Response deleteCustomerById(@PathParam("id") Integer id) 
	{		
		return Response.status(202).entity("Customer deleted successfully !!").build();
	}
}
