package com.gh.gamecenter.common.retrofit;

import android.content.Context;

import com.gh.gamecenter.core.utils.GzipUtils;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.gamecenter.common.utils.TimestampUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by LGT on 2016/11/8.
 */
public class OkHttpNetworkInterceptor implements Interceptor {

    // 空 JSONArray ResponseBody
//	private static final ResponseBody EMPTY_ARRAY_BODY = ResponseBody.create(
//			MediaType.parse("application/json"), "[]".getBytes());
    private static final ResponseBody EMPTY_ARRAY_BODY = new ResponseBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse("application/json");
        }

        @Override
        public long contentLength() {
            return 2;
        }

        @Override
        public BufferedSource source() {
            Buffer buffer = new Buffer();
            buffer.write(GzipUtils.compressBytes("[]".getBytes())); //某些接口不适配 弃用
//            buffer.write("[]".getBytes());
            return buffer;
        }
    };

    private final Context mContext;

    public OkHttpNetworkInterceptor(Context context) {
        mContext = context;
    }

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

        // 添加gzip，默认是添加的
//		request = request.newBuilder()
//				.header("Accept-Encoding", "gzip")
//				.removeHeader("Accept-Encoding")
//				.build();

        Response response = chain.proceed(request);

        // 404 Not Found
//        if (response.code() == 404) {
//            response = response.newBuilder()
//                    .code(200)
//                    .message("OK")
//                    .body(EMPTY_ARRAY_BODY)
//                    .build();
//        }

        // 缓存设置
        if (NetworkUtils.isNetworkConnected(mContext)) {
            // 有网络时，根据Cache-Control设置
            response.newBuilder()
                    .header("Cache-Control", "public, max-age=" + getMaxAge(response.header("Cache-Control")))
                    .removeHeader("Pragma")
                    .build();
        } else {
            int maxStale = 7 * 24 * 60 * 60;
            response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .removeHeader("Pragma")
                    .build();
        }

        // 如果url包含timestamp，去除timestamp再存一份缓存
        String url = response.request().url().toString();
        if (response.code() == 200 && url.contains("timestamp")) {
            OkHttpCache.putCache(mContext, TimestampUtils.removeTimestamp(url), response.peekBody(Integer.MAX_VALUE - 1).bytes());
        }

        return response;
    }

    private long getMaxAge(String headerValue) {
        long maxAge = 0;
        if (headerValue != null) {
            String[] tokens = headerValue.split(",");
            for (String token : tokens) {
                token = token.trim();
                if (token.equals("no-cache") || token.equals("no-store")) {
                    maxAge = 0;
                } else if (token.startsWith("max-age=")) {
                    try {
                        maxAge = Long.parseLong(token.substring(8));
                    } catch (Exception e) {
                        maxAge = 0;
                    }
                } else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
                    maxAge = 0;
                }
            }
        }
        return maxAge;
    }

}
