package com.gh.gamecenter.common.retrofit;

import android.content.Context;
import android.text.TextUtils;

import com.therouter.TheRouter;
import com.gh.gamecenter.common.constant.RouteConsts;
import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.gamecenter.common.utils.TimestampUtils;
import com.gh.gamecenter.core.provider.IAppProvider;
import com.gh.gamecenter.core.provider.IBuildConfigProvider;
import com.gh.gamecenter.core.provider.IPackageUtilsProvider;
import com.gh.gamecenter.core.provider.IUserManagerProvider;
import com.gh.gamecenter.core.utils.GzipUtils;
import com.lightgame.utils.Utils;

import java.io.IOException;

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

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

    private Context mContext;

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

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

        // 拦截参数缺失的非法请求
        if (request.url().pathSegments().contains("")) {
            IBuildConfigProvider buildConfig = TheRouter.get(IBuildConfigProvider.class);
            if (buildConfig.isDebug()) {
                Utils.log("OkHttpCacheInterceptor-> 已拦截参数缺失的请求：" + request.url().toString());
            }
            return new Response.Builder()
                    .code(404)
                    .request(request)
                    .protocol(Protocol.HTTP_2)
                    .body(ResponseBody.create(MediaType.parse("application/json"), "{}"))
                    .message("missing url path")
                    .build();
        }

        // 添加timestamp
        String url = request.url().toString();
        request = request.newBuilder()
                .url(TimestampUtils.addTimestamp(url))
                .build();

        // 添加渠道和版本
        if (!url.contains("version")) {
            url = request.url().toString();
            request = request.newBuilder()
                    .url(addVersionAndChannel(url))
                    .build();
        }

        // 添加用户 mark
        if (url.contains("/games:search")
                || url.contains("/home/")
                || url.contains("/settings")) {
            url = request.url().toString();
            request = request.newBuilder()
                    .url(appendUserMarkIfNeeded(url))
                    .build();
        }

        // 无网络连接时使用缓存
        if (!NetworkUtils.isNetworkConnected(mContext)) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }

        IAppProvider appProvider = TheRouter.get(IAppProvider.class);
        IUserManagerProvider userManagerProvider = TheRouter.get(IUserManagerProvider.class);
        IPackageUtilsProvider packageUtilsConfig = TheRouter.get(IPackageUtilsProvider.class);
        String token = userManagerProvider.getToken();
        String deviceId = appProvider.getGid();
        String temporaryLocalDeviceId = appProvider.getTemporaryLocalDeviceId();
        if (!TextUtils.isEmpty(token)) {
            request = request.newBuilder()
                    .addHeader("TOKEN", token)
                    .build();
        }

        if (!TextUtils.isEmpty(deviceId)) {
            request = request.newBuilder()
                    .addHeader("DEVICE", deviceId)
                    .addHeader("GID", deviceId)
                    .build();
        }

        if (!TextUtils.isEmpty(temporaryLocalDeviceId)) {
            request = request.newBuilder()
                    .addHeader("TemporaryDevice", temporaryLocalDeviceId)
                    .build();
        }

//        try {
        //noinspection ConstantExpression
//            if (request.url().toString().contains(Config.SENSITIVE_API_HOST)
//                    && BuildConfig.FLAVOR != "internal") {
//                byte[] result = AntiBotHelper.getManager().avmpSign(3, bodyToString(request.body()).getBytes("UTF-8"));
//                String wToken = new String(result, "UTF-8");
//                request = request.newBuilder()
//                        .addHeader("wToken", wToken)
//                        .build();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        request = request.newBuilder()
                .addHeader("JNFJ", MetaUtil.getBase64EncodedIMEI())
                .addHeader("CHANNEL", appProvider.getChannel())
                .addHeader("VERSION", packageUtilsConfig.getGhVersionName())
                .addHeader("OAID", appProvider.getOaid())
                .addHeader("DIA", MetaUtil.getBase64EncodedAndroidId())
                .removeHeader("User-Agent")
                .addHeader("User-Agent", appProvider.getUserAgent())
                .build();

        Response response = chain.proceed(request);

        // 去除timestamp拿缓存
        url = response.request().url().toString();
        // GET 以外的请求不取缓存来响应
        if (response.code() == 504 && url.contains("timestamp") && "GET".equals(request.method())) {
            byte[] data = OkHttpCache.getCache(mContext, TimestampUtils.removeTimestamp(url));
            if (data != null) {
                data = GzipUtils.decompressBytes(data);
                response = response.newBuilder()
                        .code(200)
                        .message("OK")
                        .body(ResponseBody.create(MediaType.parse("application/json"), data))
                        .build();
            }
        }
        return response;
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            if (copy != null) {
                final Buffer buffer = new Buffer();
                copy.writeTo(buffer);
                return buffer.readUtf8();
            } else {
                return "";
            }
        } catch (final IOException e) {
            return "did not work";
        }
    }

    /*
     * 为 url 添加 version 和 channel
     */
    private String addVersionAndChannel(String url) {
        if (TextUtils.isEmpty(url)) return url;
        IBuildConfigProvider buildConfigProvider = TheRouter.get(IBuildConfigProvider.class);
        IAppProvider appProvider = TheRouter.get(IAppProvider.class);
        if (url.contains("?")) {
            return url + "&version=" + buildConfigProvider.getVersionName() + "&channel=" + appProvider.getChannel();
        } else {
            return url + "?version=" + buildConfigProvider.getVersionName() + "&channel=" + appProvider.getChannel();
        }
    }

    /*
     * 为 url 添加用户 mark
     */
    private String appendUserMarkIfNeeded(String url) {
        IAppProvider appProvider = TheRouter.get(IAppProvider.class);
        if (TextUtils.isEmpty(url)
                || TextUtils.isEmpty(appProvider.getServerUserMark())
                || url.contains("mark=")) {
            return url;
        }

        if (url.contains("?")) {
            return url + "&mark=" + appProvider.getServerUserMark();
        } else {
            return url + "?mark=" + appProvider.getServerUserMark();
        }
    }

}
