package com.zhaohaoting.framework.requset.rxjava_retrofit;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhaohaoting.framework.utils.Logger;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * author：Created by ZHT on 2017/11/13 15:17
 * email：526309416@qq.com
 * desc：子类可定制 根据结果BASE_DATA判断成功返回数据还是失败
 */
public abstract class BaseRetrofitHelper<API> {
    private Retrofit retrofit;
    private OkHttpClient okHttpClient;

    protected API getApiService(Class<API> apiClass, String baseUrl) {
        init(baseUrl);
        return retrofit.create(apiClass);
    }

    private void init(String BaseUrl) {
        Gson gson = new GsonBuilder().create();

        okHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(getInterceptor())
                .followRedirects(true)
                .followSslRedirects(true)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(BaseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();

    }

    protected Interceptor getInterceptor() {
        return new LoggingInterceptor();
    }

    public class LoggingInterceptor implements Interceptor {
        private final Charset UTF8 = Charset.forName("UTF-8");

        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request();
            RequestBody requestBody = request.body();
            String body = null;

            if (requestBody != null) {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                body = buffer.readString(charset);
            }

            long startNs = System.nanoTime();
            Response response = chain.proceed(request);
            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

            ResponseBody responseBody = response.body();
            String rBody = null;

            if (responseBody != null) {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    try {
                        charset = contentType.charset(UTF8);
                    } catch (UnsupportedCharsetException e) {
                        e.printStackTrace();
                    }
                }
                rBody = buffer.clone().readString(charset);
            }
            Logger.e("request", request.method() + "  " + request.url() + "  " + request.headers() + "\n" + body);
            Logger.e("response",  response.code() + rBody);

            return response;
        }
    }

}
