<?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 Translates an IP Address into City, Country, Region, Zipcode, Latitude, Longitude, Time/Zone
  *
  * Returns null if someting failed.
  */
class IpGeoLocator
{
	public static function locate($ip, &$errorMessage){
		if(!$ip || empty($ip)){
			$errorMessage = "IpGeoLocator: No ip given";
			return null;
		}
	
		$config = new WebserviceConfig();
		$baseUrl = $config->getConfig("geoipservice");
		if(!$baseUrl || empty($baseUrl)){
			$errorMessage = "IpGeoLocator: No geo ip service base url set (see config \"geoipservice\")";
			error_log($errorMessage);
			return null;
		}
	
		$client = new \GuzzleHttp\Client
		(
			[
				"base_uri" => $baseUrl,
				"timeout" => 5.0,
				"http_errors" => false,
			]
		);
		$response = $client->get("/json/". $ip);
		if(is_null($response)){
			$errorMessage = "IpGeoLocator: Failed to fetch ip";
			return null;
		}
		if($response->getStatusCode() != 200){
			if($response->getStatusCode() == 403){
				$errorMessage = "IpGeoLocator: Probably too many ". $baseUrl ." requests (>10000/hour). Reason:". $response->getReasonPhrase();
			}
			else{
				$errorMessage = "IpGeoLocator: Request failed with code ". $response->getStatusCode() ." and reason ". $response->getReasonPhrase();
			}
			error_log($errorMessage);
			return null;
		}

		$body = $response->getBody();
		if(empty($body)){
			$errorMessage = "IpGeoLocator: Returned empty body";
			error_log($errorMessage);
			return null;
		}
		$json = json_decode($body, TRUE);
		if(is_null($json) || !$json || !is_array($json)){
			$errorMessage = "IpGeoLocator: Could not convert answer into json data\n". $body;
			error_log($errorMessage);
			return null;
		}
		
		$location = new Location($json["city"], $json["zip_code"],
								 $json["region_name"], $json["region_code"],
								 $json["country_name"], $json["country_code"],
								 $json["latitude"], $json["longitude"],
								 $json["time_zone"]);
		return $location;
	}
}

?>
