package com.hw.nativeapp.httpnet;

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

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.hw.nativeapp.MApplication;
import com.hw.nativeapp.config.Contents;
import com.hw.nativeapp.utils.LogUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import okhttp3.CacheControl;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * Created by kaka on 2018/3/15.
 * email:375120706@qq.com
 */

public class OkHttpInterceptor implements Interceptor {
//
//    public static final String Authorization = "Authorization";

    private static final String TAG = OkHttpInterceptor.class.getSimpleName();
    //设缓存有效期为1天
    private static final long CACHE_CONTROL_CACHE = 60 * 60 * 24 * 1L;

    public OkHttpInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        //从chain对象中可以获取到request和response，想要的数据都可以从这里获取
        Request request = chain.request();
        if (!NetworkUtils.isConnected()) {//如果不能上网，那么启用缓存
            request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }

        //增加头部信息
        request = addHeaders(request);
        //打印request日志
        logForRequest(request);
        //获取response对象
        Response response = chain.proceed(request);
//        getToken(response);

        //打印response日志
        logForResponse(response);

        if (response.code() == 401){
//            App.logout(App.getInstance());
//            ResponseConsumer.showErrorMsg("登录过期");
//            MApplication.loginout(false, "登录过期", null);
        }
        if (NetworkUtils.isConnected()) {
            //有网的时候读接口上的@Headers里的配置，可以在这里进行统一的设置
            String cacheControl = request.cacheControl().toString();
            return response.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        } else {
            return response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + CACHE_CONTROL_CACHE)
                    .removeHeader("Pragma")
                    .build();
        }

    }

    private Request addHeaders(Request request) {
        Map<String, String> params = new HashMap<>();

        String accessToken = SPUtils.getInstance().getString(Contents.SPU_TOKEN_KEY);
        if (!TextUtils.isEmpty(accessToken)) {
            params.put(Contents.TOKEN_HEAD, accessToken);
        }
        Headers headers = Headers.of(params);
        return request.newBuilder().headers(headers).build();
    }

    private String getLanguage() {
        int language = SPUtils.getInstance().getInt("language", 100);
        if (language == 100) {
            if (Locale.getDefault().equals(Locale.ENGLISH)) {
                language = 0;
            }  else {
                language = 1;
            }
        }
        switch (language){
            case 0:
                return "en";
            case 1:
                return "zh";
        }
        return "zh";
    }

    private void logForResponse(Response response) {
//        LogUtils.d("code: " + response.code());
//        LogUtils.d("protocol: " + response.protocol());
        Headers headers = response.headers();
//        if (headers != null && headers.size() != 0) {
//            LogUtils.i(headers.toString());
//        }
        try {
            //这里不能直接用response.body().string(),因为调用改方法后流就关闭，程序就可能会发生异常
            //我们需要创建出一个新的ResponseBody给应用层调用
            ResponseBody body = response.peekBody(1024 * 1024);
            if (body != null) {
                String result = body.string();
                LogUtils.d("result : " + result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void logForRequest(Request request) {
        LogUtils.d("url: " + request.url());

        Headers headers = request.headers();
        if (headers != null && headers.size() != 0) {
//            LogUtils.i("headers: " + headers.toString());
        }

        RequestBody body = request.body();
        if (body != null) {
            Buffer buffer = new Buffer();
            try {
                body.writeTo(buffer);
                LogUtils.d("body params : " + buffer.snapshot().utf8());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
