package com.zx.ad.modulecommon.net;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DecryptInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        MediaType mediaType = response.body().contentType();
        String body = response.body().string();
//        LogUtils.d("DecryptInterceptor", "response: " + body);
        try {
            JSONObject jsonObject = new JSONObject(body);
            int status = jsonObject.getInt("status");
            if (status == 200) {
                if (jsonObject.has("security")) {
                    String security = jsonObject.getString("security");
                    if (("SECURITY").equals(security)) {
                        if (jsonObject.has("sign") && jsonObject.has("enc")) {
                            String sign = jsonObject.getString("sign");
                            String enc = jsonObject.getString("enc");
                            String signResult = DecryptInterface.INSTANCE.DataSignVerify(enc, sign);
                           // LogUtils.d("DecryptInterceptor", "signResult: " + signResult);
                            if (("OK").equals(signResult)) {
                                String decryptResult = DecryptInterface.INSTANCE.DecryptData(enc);
                               // LogUtils.d("DecryptInterceptor", "decryptResult: " + decryptResult);
                                return response.newBuilder().body(ResponseBody.create(mediaType, decryptResult)).build();
                            }
                        }
                    }
                }
            }
            return response.newBuilder().body(ResponseBody.create(mediaType, body)).build();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return response.newBuilder().body(ResponseBody.create(mediaType, body)).build();
    }
}
