import pickle
import pandas as pd
import geopy
from geopy.geocoders import Nominatim

table=pd.concat(pickle.load( open( "save.p", "rb" ) ))
headers = table.iloc[0]
table_new  = pd.DataFrame(table.values[1:], columns=headers)

geolocator = Nominatim(user_agent="restaurant_getter")



def getLocation(locator, address, trials=0):
    if trials>10:
        print ("geocoder has timed out too many times. Giving up. Sorry")
        return None
    try:
        return locator.geocode(address)
    except geopy.exc.GeocoderUnavailable:
        print ("geocoder timed out. Trying for %d th time"%(trials+2))
        return getLocation(locator, address, trials+1)
    except geopy.exc.GeocoderTimedOut:
        print ("geocoder timed out. Trying for %d th time"%(trials+2))
        return getLocation(locator, address, trials+1)

nrestaurants=len(table_new.index)

longitudes=[]; latitudes=[]; precises=[]

for index, row in table_new.iterrows():
    print(len(longitudes), len(latitudes), len(precises))
    print( "Checking restaurant %d/%d"%(index, nrestaurants))
    precise="yes"
    if row['Restaurant'] == 'Restaurant':
        longitudes.append(-99); latitudes.append(-99)
        precises.append("this_is_nothing")
        continue
    if row['PLZ'] == '' and row['Adresse'] == '':
        print('Restaurant %s does not have address. Skipping'%row['Restaurant'])
        longitudes.append(-99); latitudes.append(-99)
        precises.append("address_empty")
        continue
    location = getLocation(geolocator,"%s %s %s"%(row['Adresse'],row['PLZ'],row['Ort']))
    if not hasattr(location,'latitude'):
        print ("Cannot find location for %s: %s %s %s. Adding only PLZ and place"%(row['Restaurant'],row['Adresse'],row['PLZ'],row['Ort']))
        location = getLocation(geolocator,"%s %s"%(row['PLZ'],row['Ort']))
        precise="only_plz"

    if location == None:
        precises.append("timeout")
        longitudes.append(-99); latitudes.append(-99)
        
    else:
        longitudes.append(location.longitude); latitudes.append(location.latitude)
        precises.append(precise)


table_new['longitude']=longitudes
table_new['latitude']=latitudes
table_new['precise']=precises


pickle.dump( table_new, open( "save_coordinates.p", "wb" ) )
