package io.ljunggren.exchange.rate.api.service;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import com.fasterxml.jackson.core.JsonProcessingException;

import io.ljunggren.exchange.rate.api.exception.ExchangeRateException;
import io.ljunggren.exchange.rate.api.model.ExchangeRate;
import io.ljunggren.json.utils.JsonUtils;

public class ExchangeRateService {
	
	private final String URI = "https://open.er-api.com/v6/latest/";
	
	public ExchangeRate getByCurrency(String currency) throws ExchangeRateException {
		HttpGet get = new HttpGet(URI + currency.toUpperCase());
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        	HttpClientResponseHandler<String> responseHandler = response -> {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            };
            String json = httpClient.execute(get, responseHandler);
            return parse(json, ExchangeRate.class);
        } catch (Exception e) {
        	throw new ExchangeRateException(e);
        }
	}

    private <T> T parse(String json, Class<T> clazz) throws Exception {
        try {
            return JsonUtils.jsonToObject(json, clazz);
        } catch (JsonProcessingException e) {
            throw new Exception("Unable to parse response");
        }
    }
}
