package com.yihu.hos.client;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Arrays;

/**
 * @created Airhead 2016/8/16.
 */
class BrokerServer {
    private String hostName;
    private String hostAddress;
    private String port;
    private Boolean enable;

    public String getHostName() {
        return hostName;
    }

    void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getHostAddress() {
        return hostAddress;
    }

    void setHostAddress(String hostAddress) {
        this.hostAddress = hostAddress;
    }

    public String getPort() {
        return port;
    }

    void setPort(String port) {
        this.port = port;
    }

    Boolean getEnable() {
        return enable;
    }

    void setEnable(Boolean enable) {
        this.enable = enable;
    }

    String getIdentity() {
        return this.hostAddress + ":" + this.port;
    }

    Response invokeSync(Request request) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String method = request.getMethod();
        if (request.getMethod().startsWith("/")) {
            method = request.getMethod().substring(1);
        }

        HttpPost httpPost = new HttpPost(hostAddress + ":" + port + method);
        CloseableHttpResponse response = null;
        Response result = new Response();
        try {
            response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() != 200) {
                EsbException esbException = new EsbException("Can not connect the server.");
                result.setError(esbException);
                result.setStackTrace(Arrays.toString(esbException.getStackTrace()));
                return result;
            }

            HttpEntity entity = response.getEntity();
            String body = EntityUtils.toString(entity, "UTF-8");
            result.setResult(body);
        } catch (IOException e) {
            e.printStackTrace();

            result.setError(e);
            result.setStackTrace(Arrays.toString(e.getStackTrace()));
        } finally {
            assert response != null;
            try {
                response.close();
                httpclient.close();
            } catch (IOException ignored) {
            }
        }

        return result;
    }

    void invokeAsync(Request request, final ResultCallback<Response> callback) {
    }

}
