package com.sheep.gamegroup.di.modules;

import com.sheep.gamegroup.model.api.ApiService;
import com.sheep.gamegroup.model.api.StringConverterFactory;
import com.sheep.gamegroup.model.cookie.CookieManager;
import com.sheep.gamegroup.model.util.AddPublicParamsIntercept;
import com.sheep.gamegroup.model.util.CacheInterceptor;
import com.sheep.gamegroup.model.util.EntityUtils;
import com.sheep.gamegroup.model.util.LogInterceptor;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;
//import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ljy on 2018/3/8.
 */

@Module
public class NetModule {
    @Provides
    @Singleton
    public OkHttpClient provideOkHttpClient() {
        LogInterceptor loggingInterceptor = new LogInterceptor(BuildConfig.XXTEA_ENCRYPT);
        loggingInterceptor.setLevel(TestUtil.isSheep() ? LogInterceptor.ELevel.NONE : LogInterceptor.ELevel.BODY);
        OkHttpClient okhttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(20,TimeUnit.SECONDS)
                .cookieJar(new CookieManager(SheepApp.getInstance()))
                .addInterceptor(new AddPublicParamsIntercept())
                .addInterceptor(new CacheInterceptor())
                .addInterceptor(loggingInterceptor)
                .build();
        return okhttpClient;
    }
    @Provides
    @Singleton
    public Retrofit provideRetrofit(OkHttpClient okhttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .client(okhttpClient)
                .baseUrl(SheepApp.getInstance().getConnectAddress().getAppUrl()+"v1/")
                .addConverterFactory(StringConverterFactory.create())
                .addConverterFactory(FastJsonConverterFactory.create())
//                .addConverterFactory(GsonConverterFactory.create(EntityUtils.gson))//
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit;
    }
    @Provides
    @Singleton
    public ApiService provideApiService(Retrofit retrofit){
        return retrofit.create(ApiService.class);
    }
}
