# -*- coding: utf-8 -*-
#example of how to use the Geocode providers with Address provider Hostip
import dbus

def validKey(name_key, arr):
	for key in arr.keys():
		if key == name_key:
			return True
			break
	else:
		return False

bus = dbus.SessionBus()

#address providers
try:
	geoclue = bus.get_object('org.freedesktop.Geoclue.Providers.Hostip', 
							   '/org/freedesktop/Geoclue/Providers/Hostip')

	#Geocode providers					  
	geonames = bus.get_object('org.freedesktop.Geoclue.Providers.Geonames',
							 '/org/freedesktop/Geoclue/Providers/Geonames')
							 
	yahoo = bus.get_object('org.freedesktop.Geoclue.Providers.Yahoo',
							'/org/freedesktop/Geoclue/Providers/Yahoo')
except:
	print "D-Bus error."

						   
geoclue_hostipInfo = geoclue.GetAddress(dbus_interface='org.freedesktop.Geoclue.Address')

#Address output
if validKey('country', geoclue_hostipInfo[1]):
	print "Country: " + geoclue_hostipInfo[1]['country']

if validKey('countrycode', geoclue_hostipInfo[1]):
	print "Country Code: " + geoclue_hostipInfo[1]['countrycode']

if validKey('locality', geoclue_hostipInfo[1]):
	print "City (locality): " + geoclue_hostipInfo[1]['locality'] + "\n"
else:
	print "The locality for this IP address is not defined. \nPlease define it at http://www.hostip.info\n"


#coordinates output
#For my city, Évora - Portugal, the Yahoo info is way off
try:
	geonames_coordinates = geonames.AddressToPosition(geoclue.GetAddress(dbus_interface='org.freedesktop.Geoclue.Address')[1], 
													  dbus_interface='org.freedesktop.Geoclue.Geocode')
except:
	print "D-Bus error. Getting the geonames position."
				 
print "Geonames"
print "latitude: " + str(geonames_coordinates[1])
print "longitude: " + str(geonames_coordinates[2])
print "altitude: " + str(geonames_coordinates[3]) + "\n"

try:
	geonames_yahoo = yahoo.AddressToPosition(geoclue.GetAddress(dbus_interface='org.freedesktop.Geoclue.Address')[1], 
											 dbus_interface='org.freedesktop.Geoclue.Geocode')
except:
	print "D-Bus error. Getting the yahoo position."
										 
print "Yahoo"
print "latitude: " + str(geonames_yahoo[1])
print "longitude: " + str(geonames_yahoo[2])
print "altitude: " + str(geonames_yahoo[3])

