package mil.dds.anet.resources;

import java.util.List;

import javax.annotation.security.PermitAll;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
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 javax.ws.rs.core.Response.Status;

import io.dropwizard.auth.Auth;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.Person;
import mil.dds.anet.beans.search.SavedSearch;
import mil.dds.anet.database.SavedSearchDao;
import mil.dds.anet.graphql.GraphQLFetcher;
import mil.dds.anet.graphql.IGraphQLBean;
import mil.dds.anet.graphql.IGraphQLResource;

@Path("/api/savedSearches")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
public class SavedSearchResource implements IGraphQLResource  {

	SavedSearchDao dao;
	
	public SavedSearchResource(AnetObjectEngine engine) { 
		this.dao = engine.getSavedSearchDao();
	}
	
	@POST
	@Path("/new")
	public SavedSearch saveSearch(@Auth Person user, SavedSearch search) {
		search.setOwner(Person.createWithId(user.getId()));
		return dao.insert(search);
	}
	
	@GET
	@GraphQLFetcher("mine")
	@Path("/mine")
	public List<SavedSearch> getMySearches(@Auth Person user) { 
		return dao.getSearchesByOwner(user);
	}
	
	@DELETE
	@Path("/{id}")
	public Response delete(@Auth Person user, @PathParam("id") Integer id) { 
		int numDeleted = dao.deleteSavedSearch(id, user);
		if (numDeleted == 1) { 
			return Response.ok().build();
		} else { 
			return Response.status(Status.NOT_FOUND).build();
		}
	}
	
	@Override
	public String getDescription() {
		return "Saved Searches";
	}

	@Override
	public Class<? extends IGraphQLBean> getBeanClass() {
		return SavedSearch.class;
	}
	
	@SuppressWarnings("rawtypes")
	public Class<List> getBeanListClass() {
		return List.class;
	}
}

@@ -361,24 +361,96 @@
 se.Status;%0A%0A
+import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;%0A%0A
 import io.dr
@@ -465,24 +465,24 @@
 .auth.Auth;%0A
-
 import mil.d
@@ -763,16 +763,57 @@
 esource;
+%0Aimport mil.dds.anet.utils.ResponseUtils;
 %0A%0A@Path(
@@ -1221,16 +1221,25 @@
 Id()));%0A
+%09%09try %7B%0A%09
 %09%09return
@@ -1259,16 +1259,151 @@
 earch);%0A
+%09%09%7D catch (UnableToExecuteStatementException e) %7B%0A%09%09%09throw ResponseUtils.handleSqlException(e, %22Duplicate name for saved search%22);%0A%09%09%7D%0A
 %09%7D%0A%09%0A%09@G

Handle unique constraint violation