package com.beanpodtech.allinone.retrofit;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.beanpodtech.allinone.utils.Contants;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

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

/**
 * @Description: token拦截器
 * @Author: 大魔王老杨
 * @Date: 4/12/21 5:35 PM
 */
public class TokenInterceptor implements Interceptor {

    private final Handler mHandler = new Handler(Looper.getMainLooper());

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);//执行请求
        String responseBodyStr = handResponse(response);//获得处理后的数据字符串
        try {
            //过滤异常以及判断token是否失效
            tokenException(responseBodyStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        assert response.body() != null;
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), responseBodyStr))
                .build();

    }

    /**
     * 判断是否被告知Token过期
     *
     * @param responseBodyStr
     * @return
     */
    private void tokenException(String responseBodyStr) throws JSONException {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(responseBodyStr);
            final int rstCode = jsonObject.getInt("code");
            if (rstCode == Contants.TOKEN_EXPIRE) {
//                ToastUtils.show("登录凭证已失效,请重新登录!");
//                AppUtil.INSTANCE.LoginOut();
            }
        } catch (JSONException e) {
            e.printStackTrace();
//            mHandler.post(() -> ToastUtils.show("服务器异常,请稍后重试..."));
        }
    }

    /**
     * 处理response
     *
     * @param response
     * @return
     * @throws IOException
     */
    private String handResponse(Response response) throws IOException {
        ResponseBody responseBody = response.body();
        assert responseBody != null;
        String responseBodyStr = responseBody.string();
        String requestUrl = response.request().url().url().toString();//请求路径
        Log.d("TokenInterceptor", responseBodyStr);
        Log.d("TokenInterceptor", requestUrl);
        return responseBodyStr;
    }

}
