#!/usr/bin/env python3

from __future__ import print_function
from geopy import Nominatim
# ~ import json
import sys

#disable ssl verification
import ssl
import geopy.geocoders
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
geopy.geocoders.options.default_ssl_context = ctx
#/

# debug print to stderr, https://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python
def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

if len(sys.argv) == 2:
    fn = sys.argv[1]
else:
    eprint("in case you do not know what you are doing, better call via e.g. `create-geojson.sh`.\n");
    eprint("expecting one argument: csv-file.");
    eprint("received "+str(len(sys.argv))+" argument(s): "+str(sys.argv));
    sys.exit(1) # exit with error

# for retreiving geo coordinates from addresses
geolocator = Nominatim(user_agent="vebit-mapper")
# lat: 0=111,1km; 1=11km; 2=1km… lng: 0=70km; 1=7km; 2=0,7km…
precision = 1

# convert csv to geojson

firstline = True
# start json list
print ( '{"type":"FeatureCollection","features":[' )
# get data from file
# ~ eprint( "opening: "+fn )
with open( fn, 'r' ) as fp:
    for place in fp:
        #error handling: expect
        arrAddress = place.split(";")
        strAddress1 = arrAddress[1]+" "+arrAddress[2]
        strAddress2 = ",".join(arrAddress[3:5])
        strAddress = strAddress1+","+strAddress2
        eprint( "looking up: "+strAddress )
        location = geolocator.geocode( strAddress )
        if location is not None: # its a class
            # done: ceil coords to hide true location in format string
            # ~ strCoordPlace = '{:s},{:.6f},{:.6f}'.format( arrAddress[3], location.latitude, location.longitude )
            # todo: auto deduplicate coords
            # ~ strFormatGeoCoord = '{:.'+str(precision)+'f},{:.'+str(precision)+'f}';
            # ~ strGeoCoord = strFormatGeoCoord.format( location.longitude, location.latitude )
            geojson = '{{"type":"Feature","geometry":{{"type":"Point","coordinates":[{:.'+str(precision)+'f},{:.'+str(precision)+'f}]}},"properties":{{"name":"anonentry","marker":"veb-it"}}}}';
            strCoordPlace = geojson.format( location.longitude, location.latitude ) 
            if firstline == False :
                print (",")
            else:
                firstline = False
            print ( strCoordPlace )
# end json list
print ( "]}" )

# exit fine
sys.exit(0)

# ~ m = folium.Map( # etc..)
# ~ m.save("filename.png")

# ~ https://github.com/python-visualization/folium/issues/35#issuecomment-164784086
# ~ https://github.com/wbkd/leaflet-mapshot
# ~ https://stackoverflow.com/questions/44800396/python-ipyleaflet-export-map-as-png-or-jpg-or-svg

# ~ m = folium.Map(location=[51, 13], zoom_start=5, tiles='Stamen Toner') # Mapbox Bright , CartoDB Positron
