package pl.helion.javaee7.klientogloszen;

/**
 * Created by kicia on 04.05.2015.
 */

import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpEntity;
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.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public abstract class ZadanieHttp extends AsyncTask<String, Void, String> {

    private String wykonajZadanie(String[] parametry) {
        String metoda = parametry[0];
        String url = parametry[1];
        String json = "";
        if (parametry.length > 2) // dostępne dodatkowe pole JSON
            json = parametry[2];
        String wynik = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpUriRequest zadanie = null;
            if ("GET".equals(metoda))
                zadanie = new HttpGet(url);
            if ("POST".equals(metoda)) {
                zadanie = new HttpPost(url);
                if (!json.isEmpty()) {
                    StringEntity entity = new StringEntity(json, "UTF-8");
                    entity.setContentType("application/json");
                    ((HttpPost) zadanie).setEntity(entity);
                }
            }
            HttpResponse httpResponse = httpclient.execute(zadanie);
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null)
                return "";
            BufferedReader czytnik = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuilder sb = new StringBuilder();
            String s = "";
            while ((s = czytnik.readLine()) != null)
                sb.append(s);
            wynik = sb.toString();
            czytnik.close();
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return wynik;
    }

    @Override
    protected String doInBackground(String... parametry) {
        return wykonajZadanie(parametry);
    }

}