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 = 15;

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

    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())
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getTrustManager())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .build();

    }

    /**
     * 创建 apiService
     */
    public static <T> T getService(Class<T> serviceClz) {
        return getService(serviceClz, Gateway.getRestUrl());
    }

    public static <T> T getService(Class<T> serviceClz, String baseUrl) {
        if (retrofitMap == null) {
            retrofitMap = new HashMap<>();
        }
        Retrofit retrofit = retrofitMap.get(baseUrl);
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(okHttpClient)
                    .addConverterFactory(new EmptyConverterFactory())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            retrofitMap.put(baseUrl, retrofit);
        }

        if (serviceMap == null) {
            serviceMap = new HashMap<>();
        }

        String key = baseUrl + serviceClz.getName();
        Object service = serviceMap.get(key);
        if (service == null) {
            service = retrofitMap.get(baseUrl).create(serviceClz);
            serviceMap.put(key, service);
        }

        return (T) service;

    }

}

