/*
 * COPYRIGHT (c) 2018 All rights reserved by HANWHA LIFE.
 */
package kr.co.zumo.app.lifeplus.network.api;

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

import java.util.concurrent.TimeUnit;

import kr.co.zumo.app.lifeplus.util.AppUtil;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * RetrofitService
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 19.]   [최초 작성]
 * @since 2018. 9. 19.
 */
class RetrofitService {

  static <T> T retrofit(String url, Class<T> className, int timeoutMs/*, String appVer, String userId, String deviceId, String token*/) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();

//    builder.addInterceptor(chain -> chain.proceed(chain.request()));

    // header 에 파라메터 추가하기
//    builder.addInterceptor(chain -> {
//      Request original = chain.request();
//
//      Request request = original.newBuilder()
//        .header("app_ver", appVer)
//        .header("id", userId)
//        .header("device_id", deviceId)
//        .header("token", token)
//        .method(original.method(), original.body())
//        .build();
//
//      return chain.proceed(request);
//    });


    if (timeoutMs > 0) {
      builder.writeTimeout(timeoutMs, TimeUnit.MILLISECONDS);
      builder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
      builder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    }

    if (AppUtil.isDebug()) {
      HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
      logging.setLevel(HttpLoggingInterceptor.Level.BODY);
      builder.addInterceptor(logging);
    }

    Gson gson = new GsonBuilder().create();
    Retrofit retrofit = new Retrofit.Builder()
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
      .addConverterFactory(GsonConverterFactory.create(gson))
      .baseUrl(url)
      .client(builder.build())
      .build();

    return retrofit.create(className);
  }
}
