package tech.starwin.network;

/**
 * Created by SiKang on 2018/9/14.
 */

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by SiKang on 2018/8/2.
 */

public class ServiceGenerator {
    private static final int TIME_OUT = 10;

    private static Retrofit retrofit;
    private static OkHttpClient okHttpClient;
    private static Map<String, Object> serviceMap;

    static {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new DefaultHeaderAddInterceptor())
                .addInterceptor(new FirebaseHeaderInterceptor())
                .build();

        serviceMap = new HashMap<>();
    }

    /**
     * 创建 apiService
     */
    public static <T> T getService(Class<T> serviceClz) {
        //如果 restUrl 改变，刷新Retrofit、清空Service缓存
        if (retrofit == null || !Gateway.getRestUrl().equals(retrofit.baseUrl())) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(Gateway.getRestUrl())
                    .client(okHttpClient)
                    .addConverterFactory(new EmptyConverterFactory())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            serviceMap.clear();
        }
        //如果map中已有 service 实例直接取出返回，否则新建
        if (serviceMap.containsKey(serviceClz.getName())) {
            return (T) serviceMap.get(serviceClz.getName());
        } else {
            return retrofit.create(serviceClz);
        }

    }

}

