import requests
import json
from geopy.geocoders import Nominatim

# url = 'http://nominatim.openstreetmap.org/'

# params = {'q': '157+High+Street,+Prestatyn,+Conwy', 'format': 'json', 'addressdetails': 1, 'limit': 1}

# response = requests.get(url, params=params).json()

# print(type(response))
# print(len(response))
# print(response)

# json_response = response[0]

# print(json.dumps(json_response, sort_keys=False, indent=4, separators=(',', ': ')))

url = 'http://nominatim.openstreetmap.org/reverse'

# geolocator = Nominatim()
geolocator = Nominatim(user_agent="Test_normalizer")  # user_agent is a parameter to the Nominatim class

address, (latitude, longitude) = geolocator.reverse("40.752067, -73.977578")
print(address, latitude, longitude)

params = {'q': '157+High+Street,+Prestatyn,+Conwy', 'format': 'json', 'addressdetails': 1, 'limit': 1}

streetname = '157 High Street'
cityname = 'Prestatyn'
statename = 'Conwy'
countryname = 'UK'
postcode = 'LL19 9AP'

address, (latitude, longitude) = geolocator.geocode({'street': streetname, 'postalcode': postcode})

print(address, latitude, longitude)


def osm_address_lookup(dict, geolocator):
    if 'address' in dict:
        streetname = dict['address'][0]
        postcode = dict['address'][-2]
        address, (latitude, longitude) = geolocator.geocode({'street': streetname, 'postalcode': postcode})
    else:
        print("No address.")

    lat = dict['location']['lat']
    lon = dict["location"]['lon']
    latlon = dict["location"]['lat'] + "," + dict["location"]['lon']
    if 'location' in dict:
        print(geolocator.reverse(latlon))
    else:
        pass

address = [
    "61 Coldharbour Lane",
    "Hayes",
    "Middlesex",
    "UB3 3EE",
    "England"
]

location = {
    "lat": "51.50828",
    "lon": "-0.4145179"
}

dict = {'address': address, 'location': location}
geolocator = Nominatim()
osm_address_lookup(dict, geolocator)

dict = {'location': location}
geolocator = Nominatim()
osm_address_lookup(dict, geolocator)
