package com.colorful.keyboard.theme.net;

import android.util.Log;

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

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;


public class AppClient {

    private static      Retrofit     bbmRetrofit;
    private static      OkHttpClient okHttpClient;
    public final static int          CONNECT_TIMEOUT = 120;
    public final static int          READ_TIMEOUT    = 120;
    public final static int          WRITE_TIMEOUT   = 120;

    public static Retrofit getWorkerRetrofit() {
        if (bbmRetrofit == null) {
            bbmRetrofit = new Retrofit.Builder()
                    .baseUrl("https://mrproductionsuhd.com/")
                    .addConverterFactory(ResponseConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(getOkHttpClient())
                    .build();
        }
        return bbmRetrofit;
    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {

                    Log.e("输出结果：",message);

                }
            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //设置 Debug Log 模式
            builder.addInterceptor(loggingInterceptor);
            builder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//设置连接超时时间
            //builder.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR);
            builder.addInterceptor(new LoggingInterceptor());
            builder.addNetworkInterceptor(new SignInterceptor());
            okHttpClient = builder.build();

        }
        return okHttpClient;
    }


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

            long requestTime = System.nanoTime();//请求发起的时间

            //Log.e("发送请求", request.headers().toString());

            Response response = chain.proceed(request);


            Headers responseHeaders = response.headers();

            int responseHeadersLength = responseHeaders.size();
           /* for (int i = 0; i < responseHeadersLength; i++){
                String headerName = responseHeaders.name(i);
              if (headerName.equals("web-Authorization")){
                  String authorization = responseHeaders.get("web-Authorization");
                  SPUtils.getInstance().put(Constant.TOKEN,authorization);
              }
              Log.e("666",SPUtils.getInstance().getString(Constant.TOKEN));
            }*/

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

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

            return response;
        }

    }

    static class SignInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            URL requestURL = originalRequest.url().url();
            System.out.println("signatureFinal_debug :URL " + requestURL);


            long time = System.currentTimeMillis();

            String token = "";

            System.out.println("signatureFinal_debug :token " + token);
//            String token = SaveDataGlobal.getString(SaveDataGlobal.USER_TOKEN, "");
            StringBuilder signature = new StringBuilder();

            System.out.println("signatureFinal_debug :signature " + signature);
            char[] charArr = signature.toString().toCharArray();
            Request requestWithUserAgent = originalRequest.newBuilder()
                    .removeHeader("User-Agent")
                    .removeHeader("User-Key")
                    .addHeader("User-Agent","com.ikeyboard.theme.neon.love/200 (2102cf82e4624c3bb94f30359139b1d4/d7b10839af1ba26bc4b64881501e6df0) Country/CN Language/zh System/android Version/23 Screen/560")
                    .addHeader("User-Key","f_M2HePkT1-XKO1y9MsJzt:APA91bG_JRru9-AuBlcAE7TwyhQf4POchj2nHGH6dqsL4nZd-2HhyMzZe1eIVy9TBCMG3avCVUYxj4dcN5FgbTv4_LGV-mAtb4x-FEMLztx79vySuH5gpBV7SdPCeBsB-4NmS5OElFwe")

//                    .addHeader("requestSrc", "APP")
                    //.addHeader("id", SPUtils.getInstance().getString(Constant.ID))
//                    .addHeader("Content-Type", "application/json; charset=utf-8")
//                    .addHeader("Accept", "application/json; charset=utf-8")
//                    .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
//                    .addHeader("publickey", "api")
//                    .addHeader("nonce", nonce)
//                    .addHeader("timestamp", ts + "")
//                    .addHeader("signature", signature)
//                    .addHeader("os", "Android")
//                    .addHeader("os_ver", android.os.Build.VERSION.SDK_INT + "")
//                    .addHeader("app_ver", ConstData.VerCode)
//                    .addHeader("udid", TextUtils.isEmpty(BaseApplication.phoneId) ? SaveDataGlobal.getString(SaveDataGlobal.PHONE_UDID, "") : BaseApplication.phoneId)
//                    .addHeader("channel_id", TextUtils.isEmpty(ConstData.channelId) ? SaveDataGlobal.getString("channel_id", "default") : ConstData.channelId)
                    .build();
            return chain.proceed(requestWithUserAgent);
        }
    }



}
