package com.zhimai.websocket.http;



import com.zhimai.websocket.util.Logger;

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

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

public class NetworkIntercepter implements Interceptor {
    private static final String TAG = "*---------------*";
    @Override
    public Response intercept(Chain chain) {
        long start = System.currentTimeMillis();
        Response response=null;
        String responseBody = null;
        String responseCode = null;
        String url = null;
        String requestBody = null;
        try {
            Request request = chain.request();
            url = request.method()+" "+request.url().toString();
            requestBody = getRequestBody(request);
            response = chain.proceed(request);
            responseBody = response.body().string();
            responseCode = String.valueOf(response.code());
            MediaType mediaType = response.body().contentType();
            response = response.newBuilder().body(ResponseBody.create(mediaType,responseBody)).build();
        }
        catch (Exception e){
            Logger.e(TAG,e.getMessage());
        }
        finally {
            long end = System.currentTimeMillis();
            String duration = String.valueOf(end - start);
//            Logger.e(TAG,("responseTime= {}, requestUrl= {}, params={}, responseCode= {}, result= {}",
//                    duration, url,requestBody,responseCode,responseBody);
            Logger.e(TAG,"responseTime="+duration);
            Logger.e(TAG,"requestUrl="+url);
            Logger.e(TAG,"params="+requestBody);
            Logger.e(TAG,"responseCode="+responseCode);
            Logger.e(TAG,"result="+responseBody);
        }

        return response;
    }

    private String getRequestBody(Request request) {
        String requestContent = "";
        if (request == null) {
            return requestContent;
        }
        RequestBody requestBody = request.body();
        if (requestBody == null) {
            return requestContent;
        }
        try {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = Charset.forName("utf-8");
            requestContent = buffer.readString(charset);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return requestContent;
    }
}
