#%% Process EWR Data for use in OceanMesh2D

# Alexander Rey, July 12 2022

# %% Import
import pandas as pd
import geopandas as gp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cm as cm

from shapely.geometry import Point, MultiPoint, Polygon
import alphashape

import cartopy.crs as ccrs
import contextily as ctx

# %% Import Bathymetry Points to find Concave Hull

bathyPoints = pd.read_csv("//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/00_Grid/OceanMesh/TR_Bathy.xyz",
                          header=None, names=["x", "y", "z"], delim_whitespace=True)

# Convert to Geopandas
bathyPoints_gdf = gp.GeoDataFrame(bathyPoints, geometry=gp.points_from_xy(bathyPoints.x, bathyPoints.y),
                                  crs="epsg:32615")


# %% Find Concave Hull

alphaPoints = list(map(tuple, np.column_stack((bathyPoints_gdf['x'], bathyPoints_gdf['y']))))

# Find the concave hull using the alphashape package
alphaPoly = alphashape.alphashape(alphaPoints, 0.02)


# %% Test Plot of Concave Hull
fig, axes = plt.subplots(nrows=1, ncols=1, subplot_kw={'projection': ccrs.epsg(32615)}, figsize=(10, 10))
fig.patch.set_facecolor('white')

axes.set_xlim(468545, 511043)
axes.set_ylim(5514782, 5546325)

# Add basemap
mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckemxgtk51fgp19nybfmdcb1e/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'
ctx.add_basemap(axes, source=mapbox, crs='EPSG:32615')

bathyPoints_gdf.plot('.', ax=axes, color='y', markersize=0.1)
axes.plot(*alphaPoly.exterior.xy, color='k', linewidth=1)

plt.show()

# %% Save Concave Hull to Shapefile
dataBounds = gp.GeoDataFrame(index=[0], geometry=[alphaPoly], crs='EPSG:32615')
dataBounds_wgs = dataBounds.to_crs('EPSG:4326')

dataBounds_wgs.to_file(
    '//srv-ott3.baird.com/Projects/12828.101 English Wabigoon River/06_Models/00_Delft3D/00_Grid/OceanMesh/ModelBoundsWGS.shp')


