package lc.mecha.http;

import lc.mecha.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Provides a really trivial HTTP client by wrapping {@link HttpClient} and implementing typical functions. For
 * more complex situations, use HttpClient directly.
 *
 * @author Alex Leigh
 */
public class SimpleHttpClient {
    private final HttpClient http = HttpClients.createDefault();

    public String get(String url) throws IOException {
        HttpGet get = new HttpGet(url);
        HttpResponse res = http.execute(get);
        return EntityUtils.toString(res.getEntity());
    }

    public String post(String url, String content) throws IOException {
        HttpPost post = new HttpPost(url);
        post.setEntity(new InputStreamEntity(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))));
        HttpResponse res = http.execute(post);
        return EntityUtils.toString(res.getEntity());
    }

    public String put(String url, String content) throws IOException {
        HttpPut put = new HttpPut(url);
        put.setEntity(new InputStreamEntity(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))));
        HttpResponse res = http.execute(put);
        return EntityUtils.toString(res.getEntity());
    }

    public JSONObject getJson(String url) throws IOException {
        return new JSONObject(get(url));
    }
}
