package com.libreecm.opencmis.consumers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import com.libreecm.commonAPI.auxiliars.exceptions.ErrorConsumingRESTException;
import com.libreecm.commonAPI.model.*;
import com.libreecm.commonAPI.model.objects.ObjectType;
import com.libreecm.commonAPI.model.objects.properties.PropertyDefinition;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RepositoryConsumer { 
	 
	RestTemplate restTemplate = new RestTemplate();
	ObjectMapper mapper = new ObjectMapper();
	 
	public RepositoryConsumer(){		
	} 
	
	public NewTypeSettableAttributes getNewTypeSettableAttributes(String id, String url) {
	try{
		return restTemplate.getForObject(url+"?id="+id, NewTypeSettableAttributes.class);
	} catch (HttpClientErrorException e){
		throw new ErrorConsumingRESTException(url);
	}
	
	}

	
	public Repository getRepository(String name, String url){
		Repository repository=null;
		try {
			repository = restTemplate.getForObject(url+"?name="+name, Repository.class);
		}	catch (HttpClientErrorException e){
			throw new ErrorConsumingRESTException(url);
		}
		return repository;
	}
	
	public Repository getRepositoryById(String id, String url){
		Repository repository=null;
		try {
			repository = restTemplate.getForObject(url+"?id="+id, Repository.class);
		}	catch (HttpClientErrorException e){
			throw new ErrorConsumingRESTException(url);
		}
		return repository;
	}
	
	
	public List<Repository> getRepositories(String url){
		List<Repository> repositories=null;
		try {
			repositories =  restTemplate.getForObject(url, List.class);
		} catch (HttpClientErrorException e){
			throw new ErrorConsumingRESTException(url);
		}
		List<Repository> pojos = mapper.convertValue(repositories, new TypeReference<ArrayList<Repository>>() { });
			
		return pojos;
	}
	
	
	public Repository setRepository(Repository repository, String url){
	try{	
		return restTemplate.postForObject(url, repository, Repository.class);
	} catch (HttpClientErrorException e){
		throw new ErrorConsumingRESTException(url);
	}
	}

	public List<ObjectType> getTypeChildren(String repositoryName, String typeId,
			String url) {
		List<ObjectType> result=null;
		try {
			result =  restTemplate.getForObject(url+"?repositoryName="+repositoryName+"&typeid"+typeId, List.class);
		} catch (HttpClientErrorException e){
			throw new ErrorConsumingRESTException(url);
		}
		List<ObjectType> pojos = mapper.convertValue(result, new TypeReference<ArrayList<ObjectType>>() { });
			
		return pojos;
	}

	public <T> PropertyDefinition<T> getPropertyDefinition(String id, String url){
		try{
			return restTemplate.getForObject(url+"?id="+id, PropertyDefinition.class);
		}catch (HttpClientErrorException e){
			throw new ErrorConsumingRESTException(url);
		}
	}
}
