package no.cantara.jau.clientconfig;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.regexp.internal.RE;
import no.cantara.jau.persistence.ServiceConfigDao;
import no.cantara.jau.persistence.StatusDao;
import no.cantara.jau.serviceconfig.dto.ClientConfig;
import no.cantara.jau.serviceconfig.dto.ClientRegistrationRequest;
import no.cantara.jau.serviceconfig.dto.ServiceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.ws.Service;
import java.io.IOException;

/**
 * Http endpoint for ClientStatus
 *
 * Created by jorunfa on 04/11/15.
 */
@Path(ClientResource.CLIENT_PATH)
public class ClientResource {

    public static final String CLIENT_PATH = "/client";
    private static final Logger log = LoggerFactory.getLogger(ClientResource.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    private final StatusDao statusDao;
    private final ServiceConfigDao configDao;

    @Autowired
    public ClientResource(ServiceConfigDao configDao,
                          StatusDao statusDao) {
        this.configDao = configDao;
        this.statusDao = statusDao;
    }

    @GET
    @Path("/{clientId}/status")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getStatusForAll(@PathParam("clientId") String clientId) {
        log.trace("getStatusForAll");
        ClientStatus status = statusDao.getStatus(clientId);

        String jsonResult;
        try {
            jsonResult = mapper.writeValueAsString(status);
        } catch (IOException e) {
            log.warn("Could not convert to Json {}", status.toString());
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        return Response.ok(jsonResult).build();
    }

    @GET
    @Path("/{clientId}/config")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getClientConfig(@PathParam("clientId") String clientId) {
        log.trace("Invoked getClientConfig");
        ServiceConfig serviceConfig = configDao.findByClientId(clientId);

        if (serviceConfig == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        String jsonResult;
        try {
            jsonResult = mapper.writeValueAsString(serviceConfig);
        } catch (IOException e) {
            log.warn("Could not convert to Json {}", serviceConfig.toString());
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        return Response.ok(jsonResult).build();
    }

    @PUT
    @Path("/{clientId}/config/")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response updateClientConfig(@PathParam("clientId") String clientId,
                                                        String clientConfigAsJson) {
        log.trace("Invoked updateClientConfig clientId={} with json {}", clientId,
                clientConfigAsJson);

        ClientConfig newClientConfig;
        try {
            newClientConfig = mapper.readValue(clientConfigAsJson, ClientConfig.class);
        } catch (IOException e) {
            log.error("Error parsing json. {}, json={}", e.getMessage(), clientConfigAsJson);
            return Response.status(Response.Status.BAD_REQUEST).entity("Could not parse json.").build();
        }

        String serviceConfigId = newClientConfig.serviceConfig.getId();
        ServiceConfig oldServiceConfig = configDao.changeServiceConfigForClientToUse(clientId,
                serviceConfigId);

        if (oldServiceConfig == null) {
            log.trace("ServiceConfig with id {} does not exist. Config for client {} not updated.");
            return Response.status(Response.Status.BAD_REQUEST).entity("ServiceConfig with id " +
                    serviceConfigId + " does not exist. Config for client " + clientId + " not updated.")
                    .build();
        }

        String jsonResult;
        try {
            jsonResult = mapper.writeValueAsString(oldServiceConfig);
        } catch (JsonProcessingException e) {
            log.error("{}", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
        return Response.ok(jsonResult).build();
    }

}

@@ -1641,347 +1641,39 @@
     
-String jsonResult;%0A        try %7B%0A            jsonResult = mapper.writeValueAsString(status);%0A        %7D catch (IOException e) %7B%0A            log.warn(%22Could not convert to Json %7B%7D%22, status.toString());%0A            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();%0A        %7D%0A%0A        return Response.ok(jsonResult).build(
+return mapResponseToJson(status
 );%0A 
@@ -2091,361 +2091,46 @@
     
-String jsonResult;%0A        try %7B%0A            jsonResult = mapper.writeValueAsString(serviceConfig);%0A        %7D catch (IOException e) %7B%0A            log.warn(%22Could not convert to Json %7B%7D%22, serviceConfig.toString());%0A            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();%0A        %7D%0A%0A        return Response.ok(jsonResult).build(
+return mapResponseToJson(serviceConfig
 );%0A 
@@ -2998,24 +2998,268 @@
 ig.getId();%0A
+%0A        if (configDao.findByClientId(clientId) == null) %7B%0A            return Response.status(Response.Status.BAD_REQUEST).entity(%22Client with id '%22 +%0A                    clientId + %22' does not exist.%22)%0A                    .build();%0A        %7D%0A%0A
         Serv
@@ -3461,18 +3461,41 @@
 with id 
-%7B%7D
+'%22 + serviceConfigId + %22'
  does no
@@ -3521,18 +3521,54 @@
  client 
-%7B%7D
+'%22%0A                    + clientId + %22'
  not upd
@@ -3670,16 +3670,17 @@
 with id 
+'
 %22 +%0A    
@@ -3714,16 +3714,17 @@
 igId + %22
+'
  does no
@@ -3749,17 +3749,20 @@
 r client
- 
+Id '
 %22 + clie
@@ -3769,16 +3769,17 @@
 ntId + %22
+'
  not upd
@@ -3819,32 +3819,149 @@
 d();%0A        %7D%0A%0A
+        return mapResponseToJson(oldServiceConfig);%0A    %7D%0A%0A    private Response mapResponseToJson(Object response) %7B%0A
         String j
@@ -4036,32 +4036,24 @@
 sString(
-oldServiceConfig
+response
 );%0A     
@@ -4064,30 +4064,18 @@
  catch (
-JsonProcessing
+IO
 Exceptio
@@ -4101,21 +4101,64 @@
 log.
-error(%22%7B%7D%22, e
+warn(%22Could not convert to Json %7B%7D%22, response.toString()
 );%0A 
@@ -4249,16 +4249,17 @@
       %7D%0A
+%0A
         

PUT for changing service config for single client returns bad request when client does not exist