<?php
/*
    Copyright (C) 2015 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    MA 02110-1301  USA.
*/

namespace SiWeather\Webservice;

/**
  * @brief Retrieves geo location data for different input data
  *
  * Returns null if someting failed.
  *
  * @note Requires Services_GeoNames
  */
class GeoLocator
{
	private static $_serviceBaseUrl = "http://api.geonames.org/";

	public static function configured(){
		if(empty(self::$_serviceBaseUrl))
			return false;
		if(!self::getUsername())
			return false;
		return true;
	}

	/**
		* @brief Get locations within radius @p radius around @p latitude and @p longitude.
		* 
		* Returns an array of Location objects.
		*
		* @see Location
		*/
	public static function locations($latitude, $longitude, $radius, &$errorMessage){
		if(!Location::validLatitude($latitude)){
			$errorMessage = "GeoLocator: ". $latitude ." is no valid latitude";
			return false;
		}
		if(!Location::validLatitude($longitude)){
			$errorMessage = "GeoLocator: ".$longitude ."is no valid longitude";
			return false;
		}
		if(!$radius || !is_numeric($radius) || $radius < 1){
			$errorMessage = "GeoLocator: No or invalid radius given (". $radius .")";
			return false;
		}
	
		$user = self::getUsername();
		if(!$user){
			$errorMessage = "geonames webservice not configured";
			return false;
		}

		$client = new \GuzzleHttp\Client
		(
			[
				"base_uri" => self::$_serviceBaseUrl,
				"timeout" => 2.0,								# we need a very small timeout here, because otherwise the request of our caller function may time out!
				"http_errors" => false,
			]
		);
		try{
			$response = $client->get("findNearbyPlaceNameJSON?lat=". $latitude ."&lng=". $longitude ."&username=". $user ."&lang=local&radius=". $radius ."&style=full");
		}
		catch(Exception $exception){
			$errorMessage = "GeoLocator: Fetched connect exception: ". $exception->getMessage();
			error_log($errorMessage);
			return false;
		}
		if(is_null($response)){
			$errorMessage = "GeoLocator: Failed to fetch locations";
			error_log($errorMessage);
			return false;
		}
		if($response->getStatusCode() != 200){
			if($response->getStatusCode() == 403){
				$errorMessage = "GeoLocator: Probably too many ". $baseUrl ." requests (>2000/hour or >30000/day). Reason:". $response->getReasonPhrase();
			}
			else{
				$errorMessage = "GeoLocator: Request failed with code ". $response->getStatusCode() ." and reason ". $response->getReasonPhrase();
			}
			error_log($errorMessage);
			return false;
		}

		$body = $response->getBody();
		if(empty($body)){
			$errorMessage = "GeoLocator: Returned empty body";
			error_log($errorMessage);
			return false;
		}
		$json = json_decode($body, true);
		if(is_null($json) || !$json || !is_array($json) || !array_key_exists("geonames", $json)){
			$errorMessage = "GeoLocator: Could not convert answer into json data\n". $body;
			error_log($errorMessage);
			return false;
		}
		
		$result = array();
		foreach($json["geonames"] as $geoname){
			$result[] = new Location($geoname["name"], "",
									$geoname["adminName1"], $geoname["adminCode1"],
									$geoname["countryName"], $geoname["countryCode"],
									$geoname["lat"], $geoname["lng"],
									$geoname["timezone"]["timeZoneId"]);
		}
		return $result;
	}

	private static function getUsername(){
		$webserviceConfig = new WebserviceConfig();
		$user = $webserviceConfig->getConfig("geonamesUsername");
		if(!$user || empty($user)){
			error_log("GeoLocator: No geonamesUsername set. Please adjust your webservice configuration");
			return false;
		}
		return $user;
	}
}

?>
