import urllib.request, urllib.parse, urllib.error
import json
import ssl
import sqlite3
import sys
import http
import time

api_key = False
# If you have a Google Places API key, enter it here
# api_key = 'AIzaSy___IDByT70'
# https://developers.google.com/maps/documentation/geocoding/intro

if api_key is False:
    api_key = 42
    serviceurl = 'http://py4e-data.dr-chuck.net/json?'
else :
    serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'

conn=sqlite3.connect('geo2.sqlite')
cur=conn.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS LOCATIONS (address  TEXT,geocode   TEXT)''')

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE


address=input("enter location")
cur.execute('''SELECT geocode FROM LOCATIONS WHERE address=?''',(memoryview(address.encode()),))

parms = dict()
parms['address'] = address
if api_key is not False: parms['key'] = api_key
url = serviceurl + urllib.parse.urlencode(parms)

print('Retrieving', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')

try:
     js = json.loads(data)
except:
    js = None

if not js or 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)

cur.execute('''INSERT INTO LOCATIONS(address,geocode)VALUES(?,?)''',(memoryview(address.encode()),memoryview(data.encode())))
conn.commit()

