package com.tofly.latte_core.net.base;

import com.tofly.latte_core.config.ConfigKeys;
import com.tofly.latte_core.config.Constants;
import com.tofly.latte_core.config.Latte;
import com.tofly.latte_core.net.interceptor.CommonResponseInterceptor;

import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.annotations.NonNull;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * retrofit的封装 基础类
 */
public abstract class NetWorkApi {

    //是否需要log拦截器 上线时关闭log拦截器
    private boolean isNeedLogInterceptor = Latte.getConfiguration(ConfigKeys.INTERCEPTOR.name());
    //用于存储唯一实例
    private final LinkedHashMap<String, Object> HASH_MAP = new LinkedHashMap<>();
    //baseUrl 通过配置文件存储
    private String base_url;

    protected NetWorkApi(String base_url) {
        this.base_url = base_url;
    }

    @SuppressWarnings("unchecked")
    public <T> T getRetrofitApi(Class<T> tClass) {
        //防止多次创建实例，判断一下是否保存有，如果有就直接获取，没有就保存
        if (HASH_MAP.get(base_url + tClass.getName()) != null) {
            return (T) HASH_MAP.get(base_url + tClass.getName());
        } else {
            T t = getRetrofit().create(tClass);
            HASH_MAP.put(base_url + tClass.getName(), t);
            return t;
        }
    }

//    @RequiresApi(api = Build.VERSION_CODES.N)
//    public static <T> Function<T, T> getAppHandler() {
//        return new Function<T, T>() {
//            @Override
//            public T apply(T response) {
//                if (response instanceof BaseResponse && ((BaseResponse) response).getStatus() != 0) {
//                    ExceptionHandle.ServerException exception = new ExceptionHandle.ServerException();
//                    exception.code = ((BaseResponse) response).getStatus();
//                    exception.message = ((BaseResponse) response).getMessage() != null ? ((BaseResponse) response).getMessage() : "";
//                    throw exception;
//                }
//                return response;
//            }
//        };
//    }

    private Retrofit getRetrofit() {
        // 初始化Retrofit
        return initRetrofit(initOkHttp());
    }

    /**
     * 初始化Retrofit
     */
    @NonNull
    private Retrofit initRetrofit(OkHttpClient client) {
        //base_url = Latte.getConfiguration(ConfigKeys.API_HOST.name());
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(base_url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /**
     * 初始化okHttp
     */
    public static final int DEFAULT_TIME = 30;

    @SuppressWarnings("UnnecessaryLocalVariable")
    @NonNull
    private OkHttpClient initOkHttp() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.readTimeout(DEFAULT_TIME, TimeUnit.SECONDS);//设置读取超时时间
        builder.connectTimeout(DEFAULT_TIME, TimeUnit.SECONDS);//设置请求超时时间
        builder.writeTimeout(DEFAULT_TIME, TimeUnit.SECONDS);//设置写入超时时间
        builder.retryOnConnectionFailure(true);//设置出现错误进行重新连接。
        builder.addInterceptor(getRequestInterceptor());
        builder.addInterceptor(new CommonResponseInterceptor());
        setOkHttp(builder);
        if (isNeedLogInterceptor) {
            builder.addInterceptor(getInterceptor());
        }
        OkHttpClient client = builder.build();
        return client;
    }

    //用于多域名时如果需要用到不同的拦截器
    public abstract Interceptor getInterceptor();

    public abstract Interceptor getRequestInterceptor();

    public abstract void setOkHttp(OkHttpClient.Builder builder);
}
