package no.deichman.services.resources;

import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.kohaadapter.KohaAdapter;
import no.deichman.services.repository.Repository;
import no.deichman.services.service.Service;
import no.deichman.services.service.ServiceDefault;
import no.deichman.services.utils.JSONLD;
import no.deichman.services.utils.PATCH;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.OPTIONS;
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 javax.ws.rs.core.Response.ResponseBuilder;
import java.net.URI;
import java.net.URISyntaxException;

@Path("/work")
public class WorkResource {
	
	private String _corsHeaders;

	private Response makeCORS(ResponseBuilder req, String returnMethod) {
	   ResponseBuilder rb = req.header("Access-Control-Allow-Origin", "*")
	      .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH");

	   if (!"".equals(returnMethod)) {
	      rb.header("Access-Control-Allow-Headers", returnMethod);
	   }

	   return rb.build();
	}

	private Response makeCORS(ResponseBuilder req) {
	   return makeCORS(req, _corsHeaders);
	}


    private final Service service;
    
    public WorkResource() {
        super();
        service = new ServiceDefault();
    }

    public WorkResource(KohaAdapter kohaAdapter, Repository repository) {
        super();
        ServiceDefault serviceDefault = new ServiceDefault();
        serviceDefault.setKohaAdapter(kohaAdapter);
        serviceDefault.setRepository(repository);
        service = serviceDefault;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createWork(String work) throws URISyntaxException {
        String workId = service.createWork(work);
        URI location = new URI(workId);

        return Response.created(location)
                       .header("Access-Control-Allow-Origin", "*")
                       .header("Access-Control-Allow-Methods", "POST")
                       .header("Access-Control-Expose-Headers", "Location")
                       .allow("OPTIONS")
                       .build();
    }

    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    public Response updateWork(String work) {
        service.updateWork(work);
        return Response.ok()
                       .header("Access-Control-Allow-Origin", "*")
                       .header("Access-Control-Allow-Methods", "PUT")
                       .allow("OPTIONS")
                       .build();
    }

    @PATCH
    @Consumes("application/n-triples")
    public Response patchWork(String work) {
//TODO        service.updateWork(work);

        return Response.ok()
                       .header("Access-Control-Allow-Origin", "*")
                       .header("Access-Control-Allow-Methods", "PATCH")
                       .allow("OPTIONS")
                       .build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response listWork() {
        Model model = service.listWork();

        if (model.isEmpty()) {
            throw new NotFoundException();
        }

        return Response.ok().entity(JSONLD.getJson(model))
                       .header("Access-Control-Allow-Origin", "*")
                       .header("Access-Control-Allow-Methods", "GET")
                       .allow("OPTIONS")
                       .build();
    }

    @GET
    @Path("{workId: [a-zA-Z0-9_]+}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getWorkJSON(@PathParam("workId") String workId) {
        Model model = service.retrieveWorkById(workId);

        if (model.isEmpty()) {
            throw new NotFoundException();
        }

        return Response.ok().entity(JSONLD.getJson(model))
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Methods", "GET")
                            .allow("OPTIONS")
                            .build();
    }

    @OPTIONS
    @Produces(MediaType.APPLICATION_JSON)
    public Response corsWorkBase(@HeaderParam("Access-Control-Request-Headers") String reqHeader) {
        _corsHeaders = reqHeader;
        return makeCORS(Response.ok(), reqHeader);
    }

    @OPTIONS
    @Path("{workId: [a-zA-Z0-9_]+}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response corsWorkId(@HeaderParam("Access-Control-Request-Headers") String reqHeader) {
        _corsHeaders = reqHeader;
        return makeCORS(Response.ok(), reqHeader);
    }

    @GET
    @Path("{workId: [a-zA-Z0-9_]+}/items")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getWorkItems(@PathParam("workId") String workId) {
        Model model = service.retrieveWorkItemsById(workId);
        if (model.isEmpty()) {
            throw new NotFoundException();
        }

        return Response.ok().entity(JSONLD.getJson(model))
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Methods", "GET")
                            .allow("OPTIONS")
                            .build();
    }
}

@@ -866,40 +866,8 @@
 ce %7B
-%0A%09%0A%09private String _corsHeaders;
 %0A%0A%09p
@@ -909,17 +909,18 @@
 ilder re
-q
+sp
 , String
@@ -963,17 +963,34 @@
  rb = re
-q
+sp%0A               
 .header(
@@ -1028,24 +1028,29 @@
 %22*%22)%0A%09      
+     
 .header(%22Acc
@@ -1251,103 +1251,8 @@
 %09%7D%0A%0A
-%09private Response makeCORS(ResponseBuilder req) %7B%0A%09   return makeCORS(req, _corsHeaders);%0A%09%7D%0A%0A%0A
     
@@ -4093,50 +4093,8 @@
 ONS%0A
-    @Produces(MediaType.APPLICATION_JSON)%0A
     
@@ -4193,42 +4193,8 @@
 ) %7B%0A
-        _corsHeaders = reqHeader;%0A
     
@@ -4301,50 +4301,8 @@
 %7D%22)%0A
-    @Produces(MediaType.APPLICATION_JSON)%0A
     
@@ -4399,42 +4399,8 @@
 ) %7B%0A
-        _corsHeaders = reqHeader;%0A
     

Fix CORS in services.