package com.mints.goodmoney.net;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.mints.goodmoney.BuildConfig;
import com.mints.goodmoney.MintsApplication;
import com.mints.goodmoney.manager.UserManager;
import com.mints.goodmoney.mvp.model.AppRequest;
import com.mints.goodmoney.utils.AESUtils;
import com.mints.goodmoney.utils.Base64;
import com.mints.goodmoney.utils.MD5;
import com.mints.library.utils.CommonUtils;

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

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 用拦截器对传输数据加密
 * Response返回值拦截
 */
public class OkHttpInterceptor implements Interceptor {

    private String aesKey = "";

    /**
     * 实例化拦截器对象
     */
    public OkHttpInterceptor(String aesKey) {
        this.aesKey = aesKey;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        String tokenID = UserManager.getInstance().getTokenID();

        long time = System.currentTimeMillis();

        String channel = CommonUtils.getAppMetaData(MintsApplication.getContext(), "CHANNEL_NAME");

        Request request = chain.request();
        request = encrypt(request, tokenID, time, channel);//加密方法
        Request builder = request.newBuilder().
                addHeader("version", BuildConfig.VERSION_NAME).
                addHeader("token", tokenID).
                addHeader("channel", channel).
                addHeader("new-session", MD5.GetMD5Code(String.valueOf(time))).
                addHeader("last-session", Base64.encode(String.valueOf(time).getBytes("UTF-8"))).
                build();

        return chain.proceed(builder);
    }

    // json加密
    private Request encrypt(Request request, String tokenID, long time, String channel) throws IOException {
        //这个是请求的url，也就是咱们前面配置的baseUrl
        String url = request.url().toString();
        //是否加密标识
        boolean isSign = true;
        if (!TextUtils.isEmpty(url)) {
            isSign = !url.contains("common/");
        }


        //获取请求body，只有@Body 参数的requestBody 才不会为 null
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            okio.Buffer buffer = new okio.Buffer();
            requestBody.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }

            // 原始报文
            String valueStr = buffer.readString(charset);
            String checkStr = valueStr;

            //加密
            if (isSign && !TextUtils.isEmpty(valueStr)) {
                valueStr = AESUtils.encrypt(valueStr, aesKey);
            }

            // 渠道
            String channelName = "android_" + channel;

            // sign
            String requestSign = tokenID + ":" + channelName + ":" + time;
            String sign = MD5.GetMD5Code(requestSign);
            // 验证
            String check = MD5.GetMD5Code(requestSign + ":" + checkStr);

            AppRequest appRequest = new AppRequest();
            appRequest.setChannel(channelName);
            appRequest.setSign(sign);
            appRequest.setCheck(check);
            appRequest.setData(valueStr);

            RequestBody body = MultipartBody.create(contentType, new Gson().toJson(appRequest));
            request = request.newBuilder()
                    .post(body)
                    .build();
        }
        return request;
    }

    // json解密
//    private Response decrypt(Response response) throws IOException {
//        if (response.isSuccessful()) {
//            //the response data
//            ResponseBody body = response.body();
//            BufferedSource source = body.source();
//            source.request(Long.MAX_VALUE); // Buffer the entire body.
//            Buffer buffer = source.buffer();
//            Charset charset = Charset.defaultCharset();
//            MediaType contentType = body.contentType();
//            if (contentType != null) {
//                charset = contentType.charset(charset);
//            }
//            String string = buffer.clone().readString(charset);
//            //解密方法，需要自己去实现
//            String bodyString = AESUtils.decrypt(string, aesKey);
//            ResponseBody responseBody = ResponseBody.create(contentType, bodyString);
//            response = response.newBuilder().body(responseBody).build();
//        }
//        return response;
//    }

    // 表单加密
//    @Override
//    public Response intercept(Chain chain) throws IOException {
//        Request request = chain.request();
//
//        Request.Builder requestBuilder = request.newBuilder();
//        RequestBody requestBody = request.body();
//        URL url = request.url().url();
//        String urlString = url.toString();
//
//        //是否加密标识
//        boolean isSign = true;
//        if (!TextUtils.isEmpty(urlString)) {
//            isSign = !urlString.contains("common/");
//        }
//
////        UserManage instance = UserManage.getInstance();
////        String mobile = instance.getMobile();
////        if (!TextUtils.isEmpty(mobile) && isSign) {
////            mobile =AESUtils;
////        }
//
//        if (requestBody instanceof FormBody) {
//            FormBody.Builder newFormBody = new FormBody.Builder();
//            FormBody oldFormBody = (FormBody) requestBody;
//
//            for (int i = 0; i < oldFormBody.size(); i++) {
//                String name_e = oldFormBody.encodedName(i);
//                String value = oldFormBody.value(i);
//                String value_e = "";
//                if (!TextUtils.isEmpty(value) && isSign) {
//                    value_e = AESUtils.encrypt(value, aesKey);
//                } else {
//                    value_e = oldFormBody.value(i);
//                }
//                newFormBody.add(name_e, value_e);
//            }
//            requestBuilder.method(request.method(), newFormBody.build());
//        }
//
//        Request newRequest = requestBuilder
//                .addHeader("mobile", "18311400069")
//                .build();
//        Response originalResponse = chain.proceed(newRequest);
//
//        return originalResponse;
//    }

}
