package com.sybotan.android.demo.retrofit;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

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

/**
 * Created by wangmaobo on 2018/8/23.
 */
public class RetrofitFactory {

    private static String BASE_URL = "";
    private static final long TIMEOUT = 30;
    private static final long TIMEOUT2 = 10;
    public static OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new RetrofitLogInterceptor())
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .build();

    public static API mApi;

    public static API mApiPlus;

    public static synchronized API getInstance() {
        if (null == mApi || !BASE_URL.contains(Constant.ServerIP)) {
            BASE_URL = Constant.ServerIP;
            mApi = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(createGSon()))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(httpClient)
                    .build()
                    .create(API.class);
        }
        return mApi;
    }

    private static Gson createGSon() {
        return new GsonBuilder()
                .serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                .create();
    }
}
