package com.sxyz.rfid.retrofit.http;

import com.blankj.utilcode.util.NetworkUtils;
import com.sxyz.rfid.utils.LocalUtils;

import java.io.IOException;

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

public class NetCacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        boolean connected = NetworkUtils.isConnected();
        if (connected) {
            request = request.newBuilder()
                    .header("Content-Type", "application/json")
                    .header("token", LocalUtils.getLoginModel().getToken())
                    .addHeader("XX-Device-Type", "android")
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .method(request.method(), request.body())
                    .build();
            //如果有网络，缓存60s
            Response response = chain.proceed(request);
            int maxTime = 0;
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, max-age=" + maxTime)
                    .build();
        }
        //如果没有网络，不做处理，直接返回
        return chain.proceed(request);
    }

}
