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

import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.Parser;
import org.asynchttpclient.Response;

import ru.yandex.direct.http.smart.reflection.ProtoReflectionUtils;


public class ProtoResponseConverter implements ResponseConverter<Object> {
    private final Parser<? extends Message> parser;
    private final Boolean isDelimitedStream;

    @Override
    public Object convert(Response response, Type responseType) {
        try {
            if (isDelimitedStream) {
                InputStream stream = response.getResponseBodyAsStream();
                var result = new ArrayList<>();
                Message message;
                while ((message = parser.parseDelimitedFrom(stream)) != null) {
                    result.add(message);
                }
                return result;
            } else {
                return parser.parseFrom(response.getResponseBodyAsStream());
            }
        } catch (InvalidProtocolBufferException e) {
            throw new IllegalArgumentException("Cannot deserialize response", e);
        }
    }

    public ProtoResponseConverter(Class<? extends Message> protoClass, boolean isDelimitedStream) {
        this.parser = ProtoReflectionUtils.getParserForType(protoClass);
        this.isDelimitedStream = isDelimitedStream;
    }
}
