package com.sjkj.base_lib.net.utils;

import android.content.Context;
import android.util.Log;

import com.sjkj.base_lib.utils.AppTools;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Check token and post token value
 * Created by admin on 16/9/21.
 */
public class RequestInterceptor implements Interceptor {

    private final String TAG = RequestInterceptor.class.getSimpleName();
    private Context mContext;

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

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

        //create a new request builder.set customer headers.
        Request.Builder newRequestBuilder = originalRequest.newBuilder();
        try {
            newRequestBuilder.addHeader(AppTools.ACCESS_TOKEN, AppTools.getToken());
            newRequestBuilder.addHeader("user_id", AppTools.getUserId());
            newRequestBuilder.addHeader("Content-Type", "application/json;charset=utf-8");
            newRequestBuilder.addHeader("Accept", "application/json;");

            if (originalRequest.body() instanceof FormBody) {

                FormBody oldFormBody = (FormBody) originalRequest.body();
                FormBody.Builder newFormBody = new FormBody.Builder();

                for (int i = 0; i < oldFormBody.size(); i++) {
                    newFormBody.addEncoded(oldFormBody.encodedName(i), oldFormBody.encodedValue(i));
                }
                newRequestBuilder.method(originalRequest.method(), newFormBody.build());
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "RequestInterceptor: ", e);
        }

        return chain.proceed(newRequestBuilder.build());
    }

}
