package tourplaner.business;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Http Hilfsfunktionen
 */
public class HttpHelper {

    /**
     * Holt ein Image von gegebener URL
     * @param url Url als Sting
     * @return Image von der Url
     * @throws IOException Fehler beim Bild holen
     */
    public static Image httpGetImage(String url) throws IOException {
        URL urls = new URL(url);
        return ImageIO.read(urls);
    }

    /**
     * Http GET Json string vom Url string
     * @param url Url als String
     * @return Json als String
     * @throws IOException Fehler beim Json holen
     */
    public static String httpGetJsonString(String url) throws IOException {
        HttpURLConnection con = null;
        try {
            var myurl = new URL(url);
            con = (HttpURLConnection) myurl.openConnection();
            con.setRequestMethod("GET");
            StringBuilder content;
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()))) {
                String line;
                content = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    content.append(line);
                    content.append(System.lineSeparator());
                }
            }
            return content.toString();
        } finally {
            assert con != null;
            con.disconnect();
        }
    }
}
