/*
  File: ApiClient.java
  Author: Sadai Sarmiento
  Date: 4/28/2017
  
  Description: Contains a simple base class for API client implementation
*/

package net.sf.memoranda.integrations.taiga;

import java.util.Collections;

import java.util.function.Function;

import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;

import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;

public abstract class ApiClient {
	
	private AuthenticationClient authClient;
	private WebClient webClient;
	
	public ApiClient (AuthenticationClient authClient) {
		this.authClient = authClient;
		
        webClient = WebClient.create(authClient.getApiUrl(), Collections.singletonList(new JacksonJaxbJsonProvider ()));
        webClient.header("Authorization", "Bearer " + authClient.getAuthenticationContext().getAuthToken());
        webClient.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
	}
	
	public <T> T sendRequest (Function <WebClient, T> request) {
		int retries = 0;
		do {
			try {
				WebClient webClientCopy = WebClient.fromClient(webClient);
				T response = request.apply(webClientCopy);
				webClientCopy.close();
				return response;
			}
			catch (NotAuthorizedException e) {
				if (retries < 5) {
					retries ++;
					authClient.refreshAuthenticationContext();
				}
				else throw e;
			}
		} 
		while (retries < 5);
		
		return null;
	}
}