package com.dtflys.forest.backend.httpclient.response;

import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.http.ForestResponseFactory;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since 2017-05-12 17:07
 */
public class HttpclientForestResponseFactory implements ForestResponseFactory<HttpResponse> {

    private String responseContent;

    private volatile ForestResponse resultResponse;


    private String getString(String encode, HttpEntity entity) throws IOException {
        if (responseContent == null) {
            InputStream inputStream = entity.getContent();
            responseContent = IOUtils.toString(inputStream, encode);
        }
        return responseContent;
    }


    @Override
    public synchronized ForestResponse createResponse(ForestRequest request, HttpResponse httpResponse) {
        if (resultResponse != null) {
            return resultResponse;
        }
        if (httpResponse == null) {
            httpResponse = new BasicHttpResponse(
                    new BasicStatusLine(
                            new ProtocolVersion("1.1", 1, 1), 404, ""));
        }
        HttpclientForestResponse response = new HttpclientForestResponse(request, httpResponse);
//        int statusCode = httpResponse.getStatusLine().getStatusCode();
//        response.setStatusCode(statusCode);
//        httpResponse.getAllHeaders();
        HttpEntity entity = response.getHttpResponse().getEntity();
        if (entity != null) {
            try {
                String responseText = getString(request.getResponseEncode(), entity);
                response.setContent(responseText);
            } catch (IOException e) {
                throw new ForestRuntimeException(e);
            }
        }
        this.resultResponse = response;
        return response;
    }

}

@@ -854,16 +854,23 @@
 etString
+Content
 (String 
@@ -1799,24 +1799,26 @@
 lHeaders();%0A
+//
         Http
@@ -1869,24 +1869,26 @@
 etEntity();%0A
+//
         if (
@@ -1897,32 +1897,34 @@
 tity != null) %7B%0A
+//
             try 
@@ -1925,16 +1925,18 @@
   try %7B%0A
+//
         
@@ -1974,16 +1974,23 @@
 etString
+Content
 (request
@@ -2020,16 +2020,18 @@
 ntity);%0A
+//
         
@@ -2073,16 +2073,18 @@
 eText);%0A
+//
         
@@ -2109,24 +2109,26 @@
 eption e) %7B%0A
+//
             
@@ -2164,24 +2164,26 @@
 ception(e);%0A
+//
             
@@ -2176,32 +2176,34 @@
 //            %7D%0A
+//
         %7D%0A      

response content结果获取的代码移到ForestResponse子类中