package com.xunmei.common.core.http.service;

import com.xunmei.common.core.http.service.params.HttpParams;
import com.xunmei.common.core.http.service.result.ResultExecute;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * Tkk
 */
@Component
public class CustomHttpClient {

    @Autowired
    private OkHttpClient client;

    public <T> T execute(final HttpParams params, final ResultExecute resultExecute) {
        final Request request = params.toRequest();
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Response response = null;
        try {
            response = this.client.newCall(request)
                                  .execute();
            stopWatch.stop();
            return (T) resultExecute.toBody(response, params, stopWatch);
        } catch (final HttpException e) {
            throw e;
        } catch (final Exception e) {
            throw HttpException.make(e, request, stopWatch);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}
