package com.atmob.voiceai.data.api.timeout;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import atmob.okhttp3.Interceptor;
import atmob.okhttp3.OkHttpClient;
import atmob.okhttp3.Request;
import atmob.okhttp3.Response;
import atmob.retrofit2.Invocation;

public class TimeoutInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        Invocation invocation = request.tag(Invocation.class);
        Chain newChain = chain;
        if (invocation != null) {
            Method method = invocation.method();

            ConnectionTime connectionTime = method.getAnnotation(ConnectionTime.class);
            if (connectionTime != null) {
                int connectTimeout = connectionTime.connectTimeOut();
                int readTimeout = connectionTime.readTimeout();
                int writeTimeout = connectionTime.writeTimeout();
                newChain = chain
                        .withConnectTimeout(connectTimeout, TimeUnit.SECONDS)
                        .withReadTimeout(readTimeout, TimeUnit.SECONDS)
                        .withWriteTimeout(writeTimeout, TimeUnit.SECONDS);
            }
        }
        return newChain.proceed(request);
    }
}
