package de.grobskizziert.scores.controller;

import de.grobskizziert.scores.entity.GolfClub;
import de.grobskizziert.scores.entity.Weather;
import java.io.StringReader;
import javax.ejb.Stateless;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;

/**
 * @author Frank von Eitzen <fveitzen@gmail.com>
 */
@Stateless
public class WeatherService {
    
    private final static String URL             = "http://api.openweathermap.org/data/2.5/";
    private final static String PATH_WEATHER    = "weather";
    private final static String PATH_MAIN       = "main";
    
    private final static String PARAM_APPID     = "APPID";
    private final static String PARAM_LATTITUDE = "lat";
    private final static String PARAM_LONGITUDE = "lon";
    private final static String PARAM_UNITS     = "units";
    private final static String PARAM_TEMP      = "temp";
    private final static String PARAM_TEMP_MIN  = "temp_min";
    private final static String PARAM_TEMP_MAX  = "temp_max";
    private final static String PARAM_ICON      = "icon";
      
    private final Client client;

    public WeatherService() {
        this.client = ClientBuilder.newClient();
    }
    
    public Weather getWeatherForGolfClub(GolfClub golfClub) {
        
        Weather weather = new Weather();
        
        JsonReader reader = Json.createReader(new StringReader(getWeatherForGolfClubJSON(golfClub)));
        JsonObject json = reader.readObject();
        
        JsonArray weatherArray  = json.getJsonArray(PATH_WEATHER);
        JsonObject jsonWeather = weatherArray.getJsonObject(0);
        JsonObject jsonMain = json.getJsonObject(PATH_MAIN);
        
        weather.setTemperature(jsonMain.getInt(PARAM_TEMP));
        weather.setTemperatureMin(jsonMain.getInt(PARAM_TEMP_MIN));
        weather.setTemperatureMax(jsonMain.getInt(PARAM_TEMP_MAX));
        weather.setIcon(jsonWeather.getString(PARAM_ICON));
        
        return weather;

        
    }
    
    /**
     * Get the weather for the location of the golf club
     * @param golfClub
     * @return weather as json
     */
    public String getWeatherForGolfClubJSON(GolfClub golfClub) {
        
        return this.client.target(URL)
                .path(PATH_WEATHER)
                .queryParam(PARAM_APPID, "1c94a8abd7781ffa8a69154d551e77e7")
                .queryParam(PARAM_LATTITUDE, golfClub.getLattitude())
                .queryParam(PARAM_LONGITUDE, golfClub.getLongitude())
                .queryParam(PARAM_UNITS, "metric")
                .request(MediaType.APPLICATION_JSON)
                .get(String.class);
    }
    
}
