package mprj.doerj.caderno.rest;

import com.liferay.portal.kernel.util.StringPool;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.PortletPreferences;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;


public class RestServices {

	public JSONArray getRest(String dataDivulgacao, String idStatus,ActionRequest actionRequest) throws Exception{
	    Boolean array=false;
	  
	      JSONArray arr = new JSONArray();
	      
	      PortletPreferences prefs = actionRequest.getPreferences();
	        
	      String urlOrgao = prefs.getValue("urlOrgao", StringPool.BLANK);        
	      
	          final String baseUrl = urlOrgao + dataDivulgacao + "/" + idStatus;
	          URI uri = new URI(baseUrl);
	          //RestTemplate restTemplate = new RestTemplate();
	          RestTemplate restTemp = new RestTemplate();
	          ResponseEntity<String> result = restTemp.getForEntity(uri, String.class);
	          
	             JSONObject obj = new JSONObject(result.getBody());
	            
	             List<Object> arrLista = new ArrayList<Object>();
	             
	             Object objeto = obj.get("Materias"); 
	//             System.out.println(objeto);
	            
	             if (!objeto.equals(null)){
	             array=true;
		             arrLista.add(obj.getJSONObject("Materias").get("materia"));
		             
		             if (arrLista.get(0) instanceof JSONArray){
		            	 arr = obj.getJSONObject("Materias").getJSONArray("materia");
		             }else{
		            	 arr.put(obj.getJSONObject("Materias").getJSONObject("materia"));
		             }
		           
		            
	             }
	      
	        return arr;
    }
	
	
}
