package com.eactive.eai.adapter.controller;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
	
	private static final String DJB_ROOTLESS_ARRAY = "DJB_ROOTLESS_ARRAY";

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {

		if (body instanceof String) {

			return removeRootlessArrayKeyFormResponseBody((String) body);
		}

		return body;
	}

	String removeRootlessArrayKeyFormResponseBody(String body) {

		try {
			Object root = JSONValue.parse(body);

			if (root instanceof JSONObject && ((JSONObject) root).containsKey(DJB_ROOTLESS_ARRAY)) {
				JSONArray jsonArray = (JSONArray) ((JSONObject) root).get(DJB_ROOTLESS_ARRAY);
				return jsonArray.toJSONString();
			} else {
				return body;
			}
		} catch (Exception e) {
			return body;
		}

	}

}