import webbrowser

import geopandas as gpd
import matplotlib.pyplot as plt
import folium


fig = plt.figure(figsize=(6, 6))
spec = fig.add_gridspec(ncols=1, nrows=1)
plot_map = fig.add_subplot(spec[0, 0])
fig.suptitle('Selection des dalles sur une commune')


level = 'communes'
search = 'hag'

gdf_communes = gpd.read_file("../data/raster-dl.gpkg", layer=level)
communes = gdf_communes[gdf_communes['nom_com'].str.lower().str.contains(search)]
communes[['nom_com', 'insee_com']]


code = '67186'
buffer = 500

commune = gdf_communes[gdf_communes['insee_com'] == code]
commune = commune[['geometry', 'insee_com', 'nom_com']]
commune['geometry']= commune.buffer(buffer)

commune[['nom_com', 'insee_com']]

# axis[0] = commune.plot(facecolor='green', edgecolor='black', alpha=0.5)
# plot_commune_buffer = commune.plot(facecolor='green', edgecolor='black', alpha=0.5)
# ax0 = fig.add_subplot(gs[0, 0])
c1 = commune.plot(facecolor='green', edgecolor='black', alpha=0.5, ax=plot_map)
# annotate_axes(ax0, c1)
# plt.show()

gdf_dalles = gpd.read_file("../data/raster-dl.gpkg", layer='dalles_ortho_67')
dalles = gdf_dalles[['geometry', 'FILE_IMG']]

dalles_seleted = gpd.sjoin(dalles, commune, how='inner', predicate='intersects')
# dalles_seleted.plot(cmap='Greens', edgecolor='black', alpha=0.5)

# a.head(2)
nb_dalles = len(dalles_seleted)
print('Nombre de dalles:', nb_dalles)

dalles_seleted[['FILE_IMG', 'insee_com']]


# ax1 = fig.add_subplot(gs[0, 1])

# a.explore("FILE_IMG", cmap=["red"], popup=True, tooltip="FILE_IMG", legend=False, width=600, height=400, tiles="Stamen Terrain")._repr_html_()

dalles_seleted.plot(facecolor='red', edgecolor='black', alpha=0.5, ax=plot_map)
  
# Combine all the operations and display
plt.show()



m = commune.explore("insee_com", name="commune", cmap=["green"], popup=False, tooltip=False, width=800, height=400, tiles="Stamen Terrain")
m = dalles_seleted.explore("FILE_IMG", m=m, cmap=["red"], popup=True, tooltip="FILE_IMG", legend=True)
folium.LayerControl().add_to(m)
m.save("map.html")
webbrowser.open("map.html")