import pandas as pd
import geopandas as gpd

"""
Explanation: GPS tracks
http://geopandas.org/gallery/plotting_basemap_background.html#adding-a-background-map-to-plots
https://ocefpaf.github.io/python4oceanographers/blog/2015/08/03/fiona_gpx/
End of explanation
"""


df = gpd.read_file("communes-20181110.shp")

!head test.gpx

!head test.csv

# https://gis.stackexchange.com/questions/114066/handling-kml-csv-with-geopandas-drivererror-unsupported-driver-ucsv
df_tracks = pd.read_csv("test.csv", skiprows=3)
df_tracks.head()

df_tracks.columns

from shapely.geometry import LineString

# https://shapely.readthedocs.io/en/stable/manual.html

positions = df_tracks.loc[:, ["Longitude (deg)", "Latitude (deg)"]]
positions

LineString(positions.values)

# https://stackoverflow.com/questions/38961816/geopandas-set-crs-on-points
df_tracks = gpd.GeoDataFrame(geometry=[LineString(positions.values)], crs = {'init' :'epsg:4326'})
df_tracks.head()

df_tracks.plot()

communes_list = [
    "78160", # Chevreuse
    "78575", # Saint-Rémy-lès-Chevreuse
]

df = df.loc[df.insee.isin(communes_list)]

df

ax = df_tracks.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')
ax = df.plot(ax=ax, alpha=0.5, edgecolor='k')
#df.plot(ax=ax)

"""
Explanation: TODO: put the following lists in a JSON dict and make it avaliable in a public Git repository (it can be usefull for other uses)
TODO: put the generated GeoJSON files in a public Git repository
End of explanation
"""


df_tracks_wm = df_tracks.to_crs(epsg=3857)
df_wm = df.to_crs(epsg=3857)

df_tracks_wm

ax = df_tracks_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')

"""
Explanation: Convert the data to Web Mercator
End of explanation
"""


import contextily as ctx

def add_basemap(ax, zoom, url='http://tile.stamen.com/terrain/tileZ/tileX/tileY.png'):
    xmin, xmax, ymin, ymax = ax.axis()
    basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, url=url)
    ax.imshow(basemap, extent=extent, interpolation='bilinear')
    # restore original x/y limits
    ax.axis((xmin, xmax, ymin, ymax))

"""
Explanation: Contextily helper function
End of explanation
"""


ax = df_tracks_wm.plot(figsize=(16, 16), alpha=0.5, edgecolor='k')
ax = df_wm.plot(ax=ax, alpha=0.5, edgecolor='k')

#add_basemap(ax, zoom=13, url=ctx.sources.ST_TONER_LITE)
add_basemap(ax, zoom=14)
ax.set_axis_off()

"""
Explanation: Add background tiles to plot
End of explanation
"""


import fiona
fiona.supported_drivers

!rm tracks.geojson

df_tracks.to_file("tracks.geojson", driver="GeoJSON")

!ls -lh tracks.geojson

df = gpd.read_file("tracks.geojson")

df

ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')

"""
Explanation: Save selected departments into a GeoJSON file
End of explanation
"""


