package me.arimelody.aridroid;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class SimpleDownloader {

    public static JSONObject getJSONObject(URL url) throws IOException, JSONException {
        return new JSONObject(getJSONString(url));
    }

    public static JSONArray getJSONArray(URL url) throws IOException, JSONException {
        return new JSONArray(getJSONString(url));
    }

    static String getJSONString(URL url) throws IOException {
        Log.d(Constants.TAG, String.format("Fetching %s...\n", url));
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setRequestMethod("GET");
        http.setRequestProperty("User-Agent", "aridroid/" + MainActivity.VERSION);
        http.setRequestProperty("Accept", "application/json");

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = http.getInputStream().read(buffer)) != -1) {
            stream.write(buffer, 0, length);
        }

        return stream.toString();
    }

    public static Bitmap getImage(URL url) {
        try {
            Log.d(Constants.TAG, String.format("Fetching %s...\n", url));
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("User-Agent", "aridroid/" + MainActivity.VERSION);
            http.setRequestProperty("Accept", "image/*");

            InputStream stream = http.getInputStream();
            return BitmapFactory.decodeStream(stream);
        } catch (IOException e) {
            Log.w(Constants.TAG, "Failed to download image " + url);
            return null;
        }
    }

}
