package com.virjar.echo.adr.repo;

import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class APIServices {
    private static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(EchoConfig.getApiURL())
            .callFactory(createInterceptedOkHttp())
            .addConverterFactory(GsonConverterFactory.create())
            // .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    public static UserApi userApi = retrofit.create(UserApi.class);

    private static OkHttpClient createInterceptedOkHttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        // builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.2", 8888)));

        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                String token = EchoConfig.getToken();
                if (TextUtils.isEmpty(token)) {
                    Request originalRequest = chain.request();
                    return chain.proceed(originalRequest);
                }
                //自动增加登录token
                Request originalRequest = chain.request();
                Request updateRequest = originalRequest.newBuilder().header("operatorToken", token).build();
                return chain.proceed(updateRequest);
            }
        });
        return builder.build();
    }
}
