import gridgeo


url = 'http://crow.marine.usf.edu:8080/thredds/dodsC/FVCOM-Nowcast-Agg.nc'

grid = gridgeo.GridGeo(
    url,
    standard_name='sea_water_potential_temperature'
)

import fiona

schema = {
    'geometry': 'MultiPolygon',
    'properties': {'name': f'str:{len(grid.mesh)}'}
}

with fiona.open('grid.shp', 'w', 'ESRI Shapefile', schema) as f:
    f.write(
        {
            'geometry': grid.__geo_interface__,
            'properties': {'name': grid.mesh}
        }
    )

"""
Explanation: gridgeo tour
End of explanation
"""


[s for s in dir(grid) if not s.startswith('_')]

grid.mesh

print(f'The grid has {len(grid.geometry)} polygons, showing the first 5.')

grid.geometry[:5]

grid.outline

"""
Explanation: Methods
End of explanation
"""


%matplotlib inline
import cartopy.crs as ccrs
import matplotlib.pyplot as plt


fig, ax = plt.subplots(
    figsize=(12, 12),
    subplot_kw={'projection': ccrs.PlateCarree()}
)

kw = dict(linestyle='-', alpha=0.25, color='darkgray')
ax.triplot(grid.triang, **kw)
ax.coastlines(resolution='10m');

"""
Explanation: Displaying all the polygons as vectors can be costly and crash jupyter! Let's make a raster representation of them using cartopy instead.
End of explanation
"""


kw = {
    'fill': '#fd7d11',
    'fill_opacity': 0.2,
    'stroke_opacity': 1,
    'float_precision': 2,
}

geojson = grid.to_geojson(**kw)
geojson['properties']

"""
Explanation: to_geojson() method returns a styled geojson-like dict
See https://github.com/mapbox/simplestyle-spec/tree/master/1.1.0 for styling options.
End of explanation
"""


grid.__geo_interface__.keys()

"""
Explanation: or just use the __geo_interface__.
End of explanation
"""


grid.save('grid.geojson', **kw)

"""
Explanation: Saving the grid to as geojson file
End of explanation
"""


grid.save('grid.shp')

"""
Explanation: shapefile
End of explanation
"""


import folium


x, y = grid.outline.centroid.xy

m = folium.Map(location=[y[0], x[0]])
folium.GeoJson(grid.outline.__geo_interface__).add_to(m)
m.fit_bounds(m.get_bounds())

m

"""
Explanation: or just plot using folium ;-)
End of explanation
"""


