package ru.yandex.direct.http.smart.converter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.asynchttpclient.Response;

public abstract class CustomJsonResponseConverter<R> implements ResponseConverter<R> {
    protected ObjectMapper objectMapper;

    public CustomJsonResponseConverter() {
        objectMapper = buildObjectMapper();
    }

    @Override
    public R convert(Response response, Type responseType) {
        String responseBody = response.getResponseBody(StandardCharsets.UTF_8);
        JavaType javaType = objectMapper.getTypeFactory().constructType(responseType);
        R parsed;
        try {
            parsed = objectMapper.readValue(responseBody, javaType);
        } catch (IOException e) {
            throw new IllegalArgumentException("can't deserialize object", e);
        }
        return parsed;
    }

    abstract protected ObjectMapper buildObjectMapper();
}
