package com.orange.oss.cloudfoundry.cscpi;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.orange.oss.cloudfoundry.cscpi.domain.CPIResponse;


@RestController
@RequestMapping("/cpi")
public class CPIRestController {
	
	private static Logger logger=LoggerFactory.getLogger(CPIRestController.class.getName());
	
	@Autowired
	private CPIAdapter cpiAdapter;
	
	
	@RequestMapping(method=RequestMethod.POST,produces="application/json")
	public @ResponseBody JsonNode execute(@RequestBody JsonNode  request) {
		logger.info("==> received \n {}",request);
		CPIResponse response=this.cpiAdapter.execute(request);
		logger.info("cpi-core response : {}",response);
		
		
		ObjectMapper mapper = new ObjectMapper();
		JsonNode rootNode = mapper.createObjectNode(); // will be of type  ObjectNode

		if ((response.result.size() == 1) && (response.result.get(0) instanceof Boolean)) {
			((ObjectNode) rootNode).put("result", (Boolean) response.result.get(0));
		} else if (response.result.size() == 1) {
			((ObjectNode) rootNode).put("result",(String) response.result.get(0));
		} else if (response.result.size() == 0) {
			((ObjectNode) rootNode).put("result","[]");} 
		else {
				throw new RuntimeException("NOT IMPLEMENTED : multiple response for "+request.textValue());
		}	
		
		if (response.error!=null) ((ObjectNode) rootNode).put("error", mapper.valueToTree(response.error));

		
		((ObjectNode) rootNode).put("log", response.log);		
		logger.info("generated json response payload {}",rootNode.asText());
		
		return rootNode;

	}


}

@@ -564,24 +564,81 @@
 jectMapper;%0A
+import com.fasterxml.jackson.databind.node.JsonNodeType;%0A
 import com.f
@@ -1872,16 +1872,97 @@
 %09%09%7D%09%0A%09%09%0A
+%09%09((ObjectNode) rootNode).put(%22error%22, mapper.valueToTree(response.error));%0A%09%09%0A//
 %09%09if (re
@@ -1981,16 +1981,23 @@
 !=null) 
+%7B%0A//%09%09%09
 ((Object
@@ -2062,16 +2062,71 @@
 rror));%0A
+//%09%09%7D%0A//%09%09else %7B%0A//%09%09%09rootNode.put(%22error%22, null); %7D%0A//
 %0A%09%09%0A%09%09((

fix rest cpi response (need a nill attribute for error when stemcell create ok - tested with director)