package com.example.administrator.zhapp.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.administrator.zhapp.BuildConfig;
import com.example.administrator.zhapp.contans.Contans;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ruihong on 2017/8/29.
 */

public class HttpUtils {

//    private static List<T> datas = new ArrayList<>();

    private static Api api;

    private static Context context;

    private static HttpUtils instance = null;

    public static HttpUtils getInstance(Context context, String url) {
        if (instance == null) {
            instance = new HttpUtils(context, url);
        }
        return instance;
    }

    private HttpUtils(Context context, String url) {
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(getOkHttpClient(context))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = mRetrofit.create(Api.class);
        HttpUtils.context = context;
    }

    public static Api getApi(Context context) {
        return getApi(Contans.IP, context);
    }

    public static Api getDownLoadApi(Context context) {

        Retrofit mRetrofit = new Retrofit.Builder()
                .client(getOkHttpClient(context))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = mRetrofit.create(Api.class);

        return api;
    }

    public static Api getApi(String url, Context context) {

        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(getOkHttpClient(context))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = mRetrofit.create(Api.class);

        return api;
    }


    private static OkHttpClient getOkHttpClient(Context context) {
        HttpUtils.context = context;
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.addNetworkInterceptor(new TokenHeaderInterceptor());
        //OkHttp进行添加拦截器loggingInterceptor
        httpClientBuilder.addInterceptor(new LoggingInterceptor());

        //设置超时时间
        httpClientBuilder.connectTimeout(60, TimeUnit.SECONDS);
        httpClientBuilder.writeTimeout(60, TimeUnit.SECONDS);
        httpClientBuilder.readTimeout(60, TimeUnit.SECONDS);

        return httpClientBuilder.build();
    }

    public static class TokenHeaderInterceptor implements Interceptor {
        @NonNull
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            String tokenTemp = (String) SPUtils.get(context, Contans.LOGIN_TOKEN, "");
            if (!TextUtils.isEmpty(tokenTemp)) {
                String token = RSAUtils.decryptBASE64StrLocal(tokenTemp);
                String credential = "Bearer " + token;
                Request originalRequest = chain.request();
                Request updateRequest = originalRequest.newBuilder().header("Authorization", credential).build();
                return chain.proceed(updateRequest);
            }
            return chain.proceed(chain.request());
        }
    }

    public static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            //这个chain里面包含了request和response，所以你要什么都可以从这里拿
            Request request = chain.request();

            long t1 = System.nanoTime();//请求发起的时间
            showLog(String.format("发送请求 %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);

            long t2 = System.nanoTime();//收到响应的时间

            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
            //个新的response给应用层处理
            ResponseBody responseBody = response.peekBody(1024 * 1024);

            showLog(String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
                    response.request().url(),
                    responseBody.string(),
                    (t2 - t1) / 1e6d,
                    response.headers()));

            return response;
        }
    }

    public static void showLog(String logText) {
        if (BuildConfig.LOG_ERROR) {
            if (TextUtils.isEmpty(logText)) {
                Log.i("app", "logText is null");
            } else {
                Log.i("app", logText);
            }
        }
    }
}