package com.sheep.gamegroup.model.util;

import android.text.TextUtils;

import com.sheep.gamegroup.util.LogUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;

import org.afinal.simplecache.ACache;
import org.afinal.simplecache.ApiKey;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by realicing on 2018/7/20.
 * realicing@sina.com
 */
public class CacheInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String key = request.url().toString();

        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception var27) {
            throw var27;
        }

        ResponseBody responseBody = response.body();
        if(responseBody != null) {
            long contentLength = responseBody.contentLength();

            if (HttpHeaders.hasBody(response)) {
                if (this.bodyHasUnknownEncoding(response.headers())) {
                } else {
                    BufferedSource source = responseBody.source();
                    source.request(9223372036854775807L);
                    Buffer buffer = source.buffer();

                    Charset charset = null;
                    MediaType contentType = responseBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(UTF8);
                    }
                    if (charset == null)
                        charset = UTF8;

                    if (!isPlaintext(buffer)) {
                        return response;
                    }
                    boolean oldEqualsNew = false;
                    ACache aCache = ACache.get(SheepApp.getInstance());
                    if (contentLength != 0L) {
                        String result = buffer.clone().readString(charset);
                        if (response.code() == 200 && "GET".equals(request.method())) {//成功则缓存get数据
                            LogUtil.println("sheepLog", "aCache", "key", "=", key);
                            String oldResult = aCache.getAsString(key);
                            if(TextUtils.equals(oldResult, result)){
                                oldEqualsNew = true;
                                aCache.put(ApiKey.oldEqualsNew(key), "yes");
                            } else {
                                aCache.put(key, result);
                            }
                        }
                    }
                    if(!oldEqualsNew)
                        aCache.remove(ApiKey.oldEqualsNew(key));
                }
            }
        }

        return response;
    }

    static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64L ? buffer.size() : 64L;
            buffer.copyTo(prefix, 0L, byteCount);

            for (int i = 0; i < 16 && !prefix.exhausted(); ++i) {
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }

            return true;
        } catch (EOFException var6) {
            return false;
        }
    }

    private boolean bodyHasUnknownEncoding(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity") && !contentEncoding.equalsIgnoreCase("gzip");
    }
}
