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

import java.util.function.Function;

import org.asynchttpclient.Response;

import ru.yandex.direct.asynchttp.AbstractParsableRequest;
import ru.yandex.direct.asynchttp.ParallelFetcherFactory;
import ru.yandex.direct.asynchttp.ParsableRequest;

public abstract class AbstractCall<R> {
    protected final ServiceMethod<R> serviceMethod;
    protected final ParallelFetcherFactory parallelFetcherFactory;
    protected final SmartRequestBuilder requestBuilder;
    protected final String traceFunc;

    public AbstractCall(ServiceMethod<R> serviceMethod, ParallelFetcherFactory parallelFetcherFactory,
                        SmartRequestBuilder requestBuilder) {
        this.serviceMethod = serviceMethod;
        this.parallelFetcherFactory = parallelFetcherFactory;
        this.requestBuilder = requestBuilder;
        traceFunc = serviceMethod.smart.profileName + ":" + serviceMethod.methodName;
    }

    protected ParsableRequest<R> getRequest() {
        return new AbstractParsableRequest<>(requestBuilder.getRequestId(), requestBuilder.build()) {
            @Override
            public Function<Response, R> getParseFunction() {
                return response -> serviceMethod.responseConverter.convert(response, serviceMethod.responseType);
            }

            @Override
            public boolean isParsableResponse(Response response) {
                return serviceMethod.responseChecker.check(response);
            }
        };
    }
}
