package org.fouram.core.base.service;

import java.io.IOException;

import org.fouram.core.util.LoggerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

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

@Service("requestService")
public class RequestService {

	@Autowired
	private RestTemplate restTemplate;

	// GET
	public JsonNode getForObject(String url) {
		String resultString = restTemplate.getForObject(url, String.class);
		ObjectMapper mapper = new ObjectMapper();
		JsonNode result = null;
		try {
			result = mapper.readTree(resultString);
		} catch (IOException e) {
			LoggerUtil.error(e);
		}
		return result;
	}

	// GET
	public JsonNode getForObject(String url, HttpHeaders headers) {
		ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers),
				String.class);
		ObjectMapper mapper = new ObjectMapper();
		JsonNode result = null;
		try {
			result = mapper.readTree(response.getBody());
		} catch (IOException e) {
			LoggerUtil.error(e);
		}
		return result;
	}

	// POST
	public JsonNode postForObject(String url, Object request) {
		String resultString = restTemplate.postForObject(url, request, String.class);
		ObjectMapper mapper = new ObjectMapper();
		JsonNode result = null;
		try {
			result = mapper.readTree(resultString);
		} catch (IOException e) {
			LoggerUtil.error(e);
		}
		return result;
	}
}