diff --git a/src/main/java/eirb/pg203/WeatherAPI.java b/src/main/java/eirb/pg203/WeatherAPI.java index 01d5a67..6e101b0 100644 --- a/src/main/java/eirb/pg203/WeatherAPI.java +++ b/src/main/java/eirb/pg203/WeatherAPI.java @@ -1,4 +1,68 @@ package eirb.pg203; -public class WeatherAPI { +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.time.Instant; +import java.util.ArrayList; + +public class WeatherAPI implements WeatherDataAPI{ + private final String weatherAPIKey; + + WeatherAPI(String weatherAPIKey) { + this.weatherAPIKey = weatherAPIKey; + } + + private JSONObject fetchWeather(int days, String city) throws IOException { + StringBuilder result = new StringBuilder(); + URL url = URI.create( + String.format("https://api.weatherapi.com/v1/forecast.json?key=%s&q=%s&days=%d", + this.weatherAPIKey, + city, + days + ) + ).toURL(); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(conn.getInputStream()))) { + for (String line; (line = reader.readLine()) != null; ) { + result.append(line); + } + } + + return new JSONObject(result.toString()); + } + + @Override + public Temperature getTemperature(int day, String city) throws IOException { + JSONObject result = fetchWeather(day+1, city); + JSONArray forecast = result.getJSONObject("forecast").getJSONArray("forecastday"); + float temp_c = forecast.getJSONObject(day).getJSONObject("day").getFloat("avgtemp_c"); + + return new Temperature(temp_c, city, Instant.now()); + } + + @Override + public Temperature getTemperature(int day, int hour, String city) throws IOException{ + return getTemperature(day, city); + } + + @Override + public ArrayList getTemperatures(int days, String city) throws IOException { + JSONObject result = fetchWeather(days, city); + ArrayList temperatures = new ArrayList<>(); + for (int day = 0; day < days; ++day) { + JSONArray forecast = result.getJSONObject("forecast").getJSONArray("forecastday"); + float temp_c = forecast.getJSONObject(day).getJSONObject("day").getFloat("avgtemp_c"); + temperatures.add(new Temperature(temp_c, city, Instant.now())); + } + return temperatures; + } }