package org.mockenize.service;

import java.io.IOException;
import java.util.Collection;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.mockenize.exception.ScriptNotFoundException;
import org.mockenize.model.ScriptBean;
import org.mockenize.repository.ScriptRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class ScriptService {

	private static final String ENGINE_NAME = "JavaScript";

	private static final String DEFAUL_FUNCTION_NAME = "_func";

	private static final String PARSE_FUNCTION = ""
			+ "function _func(url, body) {"
			+ "try{obj=JSON.parse(body)}catch(ex){};"
			+ "ret = func(url, body, obj);"
			+ "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};"
			+ "return ret};";

	private static final String EMPTY = "";

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private ScriptRespository scriptRespository;

	public ScriptBean getByKey(String jsName) {
		ScriptBean scriptBean = scriptRespository.findByKey(jsName);

		if (scriptBean == null) {
			throw new ScriptNotFoundException();
		}

		return scriptBean;
	}

	public ScriptBean delete(ScriptBean scriptBean) {
		return scriptRespository.delete(scriptBean.getName());
	}
	
	public Collection<ScriptBean> deleteAll() {
		return scriptRespository.deleteAll();
	}

	public void save(ScriptBean scriptBean) {
		scriptRespository.save(scriptBean);
	}

	public Collection<ScriptBean> getAll() {
		return scriptRespository.findAll();
	}

	public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body)
			throws ScriptException, NoSuchMethodException, IOException {
		ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME);
		scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue());
		Invocable invocable = (Invocable) scriptEngine;
		String stringBody = body != null ? body.toString() : EMPTY;
		return objectMapper.createObjectNode()
				.textNode(String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody)));
	}

	public Collection<String> getAllKeys() {
		return scriptRespository.findAllKeys();
	}

}

@@ -480,24 +480,78 @@
 e.Service;%0A%0A
+import com.fasterxml.jackson.core.JsonParseException;%0A
 import com.f
@@ -2201,61 +2201,21 @@
 ;%0A%09%09
-return objectMapper.createObjectNode()%0A%09%09%09%09.textNode(
+String ret = 
 Stri
@@ -2289,18 +2289,173 @@
 ngBody))
-)
 ;
+%0A%09%09try %7B%0A%09%09%09return objectMapper.readTree(ret);%0A%09%09%7D catch(JsonParseException parseException) %7B%09%09%0A%09%09%09return objectMapper.createObjectNode().textNode(ret);%0A%09%09%7D
 %0A%09%7D%0A%0A%09pu

fix bug js