package com.zztrapp.zztrapp.http;

import android.app.Activity;
import android.content.Context;

import com.zztrapp.zztrapp.utilcode.util.NetworkUtils;
import com.zztrapp.zztrapp.utilcode.util.ToastUtils;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Describe CaheInterceptor
 * Created by Bby on 2021/10/2
 * Email bby0856@163.com
 */

public class CaheInterceptor implements Interceptor {

    private Context context;

    public CaheInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (NetworkUtils.isConnected()) {
//            KLog.e("*****************isConnected");
            Response response = chain.proceed(request);
            // read from cache for 60 s
            int maxAge = 60;
            String cacheControl = request.cacheControl().toString();
            return response.newBuilder()
//                    .addHeader("Authorization", " Token "+token)
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .addHeader("Cache-Control", "public, max-age=" + maxAge)
//                    .addHeader("sign","col9j6cqegAKiiey3IrXWs2ORqPB0rVvq6fYZPajrYgIVnKDb7Rin03dOqY2qLWP") //签名
//                    .addHeader("version","1")//版本号
//                    .addHeader("apptype","android")//app类型
//                    .addHeader("did","12345dg")//手机唯一标识
//                    .addHeader("model","")//手机型号
                    .build();
        } else {
//            KLog.e("*****************isNotConnected");
            ((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showShort("网络不给力");
                }
            });
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
            Response response = chain.proceed(request);
            //set cahe times is 14 days
            int maxStale = 60 * 60 * 24 * 14;
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
    }
}
