## Plotting Mike21 SW results for SouthShore
# Author: AJMR
# December 22, 2021

# %%  Setup Project
from mikeio import Dfsu, Mesh, Dfs2, Dfs0, Dfs1

import pandas as pd
import pathlib as pl
import numpy as np
import geopandas as gp
import datetime as datetime

import matplotlib.pyplot as plt
import contextily as ctx
import matplotlib.font_manager as fm

# %% Read Model Log

pth = pl.Path("//srv-ott3.baird.com/", "Projects", "13539.101 L'Ansecoy Bay, Mustique", "06_Models",
              "Model Log Mustique.xlsx")

runLog = pd.read_excel(pth.as_posix(), "ModelLog")

# %% Read Model Results
modelPlot = range(10, 11)

curSpeed_list = [None] * (max(modelPlot) + 1)
curElm_list = [None] * (max(modelPlot) + 1)
curU_list = [None] * (max(modelPlot) + 1)
curV_list = [None] * (max(modelPlot) + 1)
curW_list = [None] * (max(modelPlot) + 1)
dfs_list = [None] * (max(modelPlot) + 1)
dfs2d_list = [None] * (max(modelPlot) + 1)
ds_list = [None] * (max(modelPlot) + 1)
wl_list = [None] * (max(modelPlot) + 1)
wd_list = [None] * (max(modelPlot) + 1)
bed_list = [None] * (max(modelPlot) + 1)
z_list = [None] * (max(modelPlot) + 1)
z_profile_list = [None] * (max(modelPlot) + 1)

elm_list = [None] * (max(modelPlot) + 1)
elm_df_list = [None] * (max(modelPlot) + 1)

elm2d_list = [None] * (max(modelPlot) + 1)
elm2d_df_list = [None] * (max(modelPlot) + 1)

readPointsName = pd.read_csv("//srv-ott3.baird.com/Projects/13539.101 L'Ansecoy Bay, Mustique/03_Data/03_Field/01_September 2021 trip/Dataset locations_RevB.csv",
                           delimiter=",")
readPoints = pd.read_csv("//srv-ott3.baird.com/Projects/13539.101 L'Ansecoy Bay, Mustique/03_Data/03_Field/01_September 2021 trip/Dataset locations_RevE.csv",
                           delimiter=",").iloc[0:, 2:-2].values


# readPoints = np.zeros((14, 2))
# readPoints[0, :] = [693000, 1425500]
# readPoints[1, :] = [697000, 1429500]
# readPoints[2, :] = [697000, 1421500]
# readPoints[3, :] = [701000, 1425500]
#
# # readPoints[4, :] = [697576.96, 1425767.10]  # RBR NEAR
# # readPoints[5, :] = [697760.89, 1426109.73]  # RBR FAR
#
# # From Mathew
# readPoints[4, :] = [697858.00, 1426095.00]  # RBR NEAR
# readPoints[5, :] = [697613.00, 1426509.00]  # RBR FAR
#
# # Location Uncertainty
# # 500 -x
# readPoints[6, :] = [697858.00-100, 1426095.00-0]  # RBR NEAR
# readPoints[7, :] = [697613.00-150, 1426509.00+150]  # RBR FAR
# # 500 +x
# readPoints[8, :] = [697858.00+100, 1426095.00-0]  # RBR NEAR
# readPoints[9, :] = [697613.00-50, 1426509.00+50]  # RBR FAR
# # 500 -x
# readPoints[10, :] = [697858.00+150, 1426095.00+150]  # RBR NEAR
# readPoints[11, :] = [697613.00+150, 1426509.00+150]  # RBR FAR
# # 500 -x
# readPoints[12, :] = [697858.00-150, 1426095.00+150]  # RBR NEAR
# readPoints[13, :] = [697613.00-150, 1426509.00+150]  # RBR FAR

#125 +125

for m in modelPlot:

    dfsIN = Dfsu(pl.Path(runLog['Run Location'][m], 'fullDomain2D.dfsu').as_posix())
    dfs2d_list[m] = dfsIN

    # Read Map
    # ds_list[m] = dfs_list[m].read()
    # curU_list[m] = ds_list[m]["Depth averaged U velocity"]
    # curV_list[m] = ds_list[m]["Depth averaged V velocity"]
    # curElm_list[m] = dfs_list[m].element_coordinates
    # wl_list[m] = ds_list[m]["Surface elevation"]
    # z_list[m] = ds_list[m]["Z coordinate"]

    ## Read specific points in 2D
    # Find nearest elements
    elem_ids = dfs2d_list[m].find_nearest_elements(readPoints[:, 0], readPoints[:, 1])
    # Read in data from nearest elements
    elm2d_list[m] = dfs2d_list[m].read(elements=elem_ids)

    # Convert to Pandas DataFrame
    elm2d_df_list[m] = [None] * readPoints.shape[0]
    for p in range(0, readPoints.shape[0]):
        elm2d_df_list[m][p] = elm2d_list[m].isel(idx=p).to_dataframe()


    ## Read specific points 3D
    # Setup MIKE object
    dfsIN = Dfsu(pl.Path(runLog['Run Location'][m], 'fullDomain3D.dfsu').as_posix())
    dfs_list[m] = dfsIN

    # Find nearest elements
    elem_ids = dfs_list[m].find_nearest_profile_elements(readPoints[:, 0], readPoints[:, 1])
    # Read from elements- flatten 2d element array (xy and z) to 1d for reading
    elm_list[m] = dfs_list[m].read(elements=elem_ids.flatten().astype(int))

    elm_df_list[m] = [None] * readPoints.shape[0]
    z_profile_list[m] = [None] * readPoints.shape[0]
    # Convert to Pandas DataFrame
    # Loop through points, selecting corresponding depths
    for p in range(0, readPoints.shape[0]):
        z_profile_list[m][p] = dfs_list[m].element_coordinates[elem_ids[p, :].astype(int), 2]

        # Convert to Pandas and add zidx
        for z in range(0, z_profile_list[m][p].shape[0]):
            df_tmp = elm_list[m].isel(idx=p * 5 + z).to_dataframe()
            df_tmp['Z'] = z_profile_list[m][p][z]
            df_tmp['Z_IDX'] = z
            if z == 0:
                elm_df_list[m][p] = df_tmp
            else:
                elm_df_list[m][p] = elm_df_list[m][p].append(df_tmp)

            del df_tmp

# %% Import RBR data
rbr_path = "C:/Users/arey/files/Projects/Mustique/041279_20211203_1541Ruskin.xlsx"
rbr_pd = pd.read_excel(rbr_path, sheet_name='Wave', parse_dates=True, header=1, index_col=0)
rbr_pd['WL'] = rbr_pd['Depth'] - rbr_pd['Depth'].mean() - 0.2

# Correct time zone
rbr_pd.index = rbr_pd.index + datetime.timedelta(hours=4)

# %% Import Nortek Eco data
eco_path_1 = "//srv-ott3/Projects/13539.101 L'Ansecoy Bay, Mustique/03_Data/03_Field/01_September 2021 trip/02_Nortek ECO/Eco61_20210910184606.csv"
eco_path_2 = "//srv-ott3/Projects/13539.101 L'Ansecoy Bay, Mustique/03_Data/03_Field/01_September 2021 trip/02_Nortek ECO/Eco214_20210902120703.csv"

eco1_pd = pd.read_csv(eco_path_1, sep=',', header=[28], index_col=0,
                      parse_dates=False)

eco2_pd = pd.read_csv(eco_path_2, sep=',', header=[28], index_col=0,
                      parse_dates=False)

# Drop first row
eco1_pd.drop(eco1_pd.index[0], inplace=True)
eco2_pd.drop(eco2_pd.index[0], inplace=True)

eco1_pd.index = pd.to_datetime(eco1_pd.index, format='%m/%d/%Y %I:%M:%S %p')
eco2_pd.index = pd.to_datetime(eco2_pd.index, format='%m/%d/%Y %I:%M:%S %p')

# Set water level to zero
eco1_pd['WL'] = eco1_pd['Depth'].astype(float) - eco1_pd['Depth'].astype(float).mean(skipna=True) + 0.2
eco2_pd['WL'] = eco2_pd['Depth'].astype(float) - eco2_pd['Depth'].astype(float).mean(skipna=True) + 0.2

# Correct time zone
eco1_pd.index = eco1_pd.index + datetime.timedelta(hours=4)
eco2_pd.index = eco2_pd.index + datetime.timedelta(hours=4)

# %% Read in boundary conditions
ds_wl = []

dfs1 = Dfs1("//oak-spillway.baird.com/D/13539.101 L'Ansecoy Bay, Mustique/MIKE3/02_Bounds/NCOM2_EastBound.dfs1")
ds_wl.append(dfs1.read())

dfs1 = Dfs1("//oak-spillway.baird.com/D/13539.101 L'Ansecoy Bay, Mustique/MIKE3/02_Bounds/NCOM2_NorthBound.dfs1")
ds_wl.append(dfs1.read())

dfs1 = Dfs1("//oak-spillway.baird.com/D/13539.101 L'Ansecoy Bay, Mustique/MIKE3/02_Bounds/NCOM2_SouthBound.dfs1")
ds_wl.append(dfs1.read())

dfs1 = Dfs1("//oak-spillway.baird.com/D/13539.101 L'Ansecoy Bay, Mustique/MIKE3/02_Bounds/NCOM2_WestBound.dfs1")
ds_wl.append(dfs1.read())

# %% Plot Water Level at a point
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(8, 8), sharex=True)
# plotstart = '2021-10-01 00:00:00'
# plotend   = '2021-10-21 00:00:00'
plotstart = '2021-10-05 00:00:00'
plotend   = '2021-10-07 00:00:00'

for sub, p in enumerate([5, 6, 9]):

    if p == 9:
        rbr_pd['WL'].plot(ax=axes[sub], color='k', label='Obervations')
    elif p == 5:
        eco1_pd['WL'].plot(ax=axes[sub], color='k', label='Obervations')
    elif p == 6:
        eco2_pd['WL'].plot(ax=axes[sub], color='k', label='Obervations')

    elm2d_df_list[m][p].plot(y='Surface elevation', ax=axes[sub], label=readPointsName.Dataset[p])

    axes[sub].set_xlim(pd.Timestamp(plotstart), pd.Timestamp(plotend))
    axes[sub].set_ylim(-1.0, 1.0)

plt.show()

# %% Plot Water Level at a 3D point
plotstart = '2021-09-14 00:00:00'
# plotend = '2021-09-16 00:00:00'
plotend = '2021-10-03 00:00:00'

fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(8, 8), sharex=True)

# elm_df_list[m][6].loc[elm_df_list[m][6]['Z_IDX'] == 4, :].plot(
#     y='Z', ax=axes[0], label='Model')

axes[0].plot(elm_df_list[m][5].loc[elm_df_list[m][5]['Z_IDX'] == 4, :].index,
             elm_list[m]['Z coordinate'][:, 30*6-1]+0.1, label='Model')
eco1_pd['WL'].plot(ax=axes[0], color='k', label='Observations')
axes[0].set_xlim(pd.Timestamp(plotstart), pd.Timestamp(plotend))
axes[0].set_ylabel('Water Level Offshore (m)')
axes[0].legend()


# elm_df_list[m][7].loc[elm_df_list[m][7]['Z_IDX'] == 4, :].plot(
#     y='Z', ax=axes[1], label='Model')
axes[1].plot(elm_df_list[m][7].loc[elm_df_list[m][7]['Z_IDX'] == 4, :].index,
             elm_list[m]['Z coordinate'][:, 14*6-1]+0.1, label='Model')
eco2_pd['WL'].plot(ax=axes[1], color='k', label='Observations')
axes[1].set_xlim(pd.Timestamp(plotstart), pd.Timestamp(plotend))
axes[1].set_ylabel('Water Level Nearshore (m)')
axes[1].legend()

axes[1].set_xlabel('Date')

plt.show()
fig.savefig('//srv-ott3.baird.com/Projects/13539.101 L\'Ansecoy Bay, Mustique/06_Models/01_MIKE3/00_Figures/' +
            '/wl_TS.png', bbox_inches='tight')

# %% Velocity point
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(8, 8), sharex=True)

eco1_pd['Upper speed'].astype(float).plot(ax=axes[0], color='tab:red', label='Observations')
elm_df_list[m][5]['Current Speed'] = np.sqrt(
    elm_df_list[m][5]['U velocity'] ** 2 + elm_df_list[m][5]['V velocity'] ** 2)
elm_df_list[m][5].loc[elm_df_list[m][4]['Z_IDX'] == 4, :].plot(
    y='Current Speed', ax=axes[0], label='Model')

axes[0].set_xlim(pd.Timestamp('2021-09-15 00:00:00'), pd.Timestamp('2021-10-3 00:00:00'))
axes[0].set_ylabel('Nearshore Eco Current')
axes[0].legend()

eco2_pd['Upper speed'].astype(float).plot(ax=axes[1], color='tab:red', label='Observations')
elm_df_list[m][5]['Current Speed'] = np.sqrt(
    elm_df_list[m][5]['U velocity'] ** 2 + elm_df_list[m][5]['V velocity'] ** 2)
elm_df_list[m][5].loc[elm_df_list[m][5]['Z_IDX'] == 4, :].plot(
    y='Current Speed', ax=axes[1], label='Model')

axes[1].set_xlim(pd.Timestamp('2021-09-15 00:00:00'), pd.Timestamp('2021-10-3 00:00:00'))
axes[1].set_ylabel('Offshore Eco Current')

plt.show()


# %% Velocity point U and V
# Z_IDX = 4
# ecoVar1 = 'Upper speed U'
# ecoVar2 = 'Upper speed V'
# ecoVar3 = 'Upper speed'
# ecoVar4 = 'Upper direction'

# plotstart = '2021-09-14 00:00:00'
# # plotend = '2021-09-16 00:00:00'
# plotend = '2021-10-03 00:00:00'

plotstart = '2021-10-01 00:00:00'
# plotend = '2021-09-16 00:00:00'
plotend = '2021-10-21 00:00:00'

Z_IDX = 2
ecoVar1 = 'Middle speed U'
ecoVar2 = 'Middle speed V'
ecoVar3 = 'Middle speed'
ecoVar4 = 'Middle direction'

# Z_IDX = 1
# ecoVar1 = 'Lower speed U'
# ecoVar2 = 'Lower speed V'
# ecoVar3 = 'Lower speed'
# ecoVar4 = 'Lower direction'

fig, axes = plt.subplots(nrows=4, ncols=1, figsize=(8, 8), sharex=True)

eco1_pd[ecoVar1] = eco1_pd[ecoVar3].astype(float) * \
                   np.sin(np.radians(eco1_pd[ecoVar4].astype(float).to_numpy()))

eco1_pd[ecoVar1].astype(float).plot(ax=axes[0], color='k', label='Observations')
elm_df_list[m][3].loc[elm_df_list[m][3]['Z_IDX'] == Z_IDX, :].plot(
    y='U velocity', ax=axes[0], label='Model')
elm_df_list[m][5].loc[elm_df_list[m][5]['Z_IDX'] == Z_IDX, :].plot(
    y='U velocity', ax=axes[0], label='Model Shift')

axes[0].set_ylim(-0.5, 0.5)
axes[0].set_xlim(pd.Timestamp(plotstart), pd.Timestamp(plotend))
axes[0].set_ylabel('Nearshore U (m/s)')
axes[0].legend(bbox_to_anchor=(0.90, 1), loc="upper left")

eco1_pd[ecoVar2] = eco1_pd[ecoVar3].astype(float) * \
                   np.cos(np.radians(eco1_pd[ecoVar4].astype(float).to_numpy()))

eco1_pd[ecoVar2].astype(float).plot(ax=axes[1], color='k', label='Observations')

elm_df_list[m][3].loc[elm_df_list[m][3]['Z_IDX'] == Z_IDX, :].plot(
    y='V velocity', ax=axes[1], label='Model')
elm_df_list[m][5].loc[elm_df_list[m][5]['Z_IDX'] == Z_IDX, :].plot(
    y='V velocity', ax=axes[1], label='Model Shift')


axes[1].set_ylim(-0.5, 0.5)
axes[1].set_xlim(pd.Timestamp(plotstart), pd.Timestamp(plotend))
axes[1].set_ylabel('Nearshore V (m/s)')
axes[1].legend(bbox_to_anchor=(0.90, 1), loc="upper left")

eco2_pd[ecoVar1] = eco2_pd[ecoVar3].astype(float) * \
                   np.sin(np.radians(eco2_pd[ecoVar4].astype(float).to_numpy()))
eco2_pd[ecoVar1].astype(float).plot(ax=axes[2], color='k', label='Observations')
elm_df_list[m][4].loc[elm_df_list[m][4]['Z_IDX'] == Z_IDX, :].plot(
    y='U velocity', ax=axes[2], label='Model')
elm_df_list[m][6].loc[elm_df_list[m][6]['Z_IDX'] == Z_IDX, :].plot(
    y='U velocity', ax=axes[2], label='Model Shift')

axes[2].set_ylim(-1.5, 1.5)
axes[2].set_xlim(pd.Timestamp(plotstart), pd.Timestamp(plotend))
axes[2].set_ylabel('Offshore U (m/s)')
axes[2].legend(bbox_to_anchor=(0.90, 1), loc="upper left")

eco2_pd[ecoVar2] = eco2_pd[ecoVar3].astype(float) * \
                   np.cos(np.radians(eco2_pd[ecoVar4].astype(float).to_numpy()))
eco2_pd[ecoVar2].astype(float).plot(ax=axes[3], color='k', label='Observations')
elm_df_list[m][4].loc[elm_df_list[m][4]['Z_IDX'] == Z_IDX, :].plot(
    y='V velocity', ax=axes[3], label='Model')
elm_df_list[m][5].loc[elm_df_list[m][5]['Z_IDX'] == Z_IDX, :].plot(
    y='V velocity', ax=axes[3], label='Model Shift')

axes[3].set_ylim(-1.00, 1.00)
axes[3].set_xlim(pd.Timestamp(plotstart), pd.Timestamp(plotend))
axes[3].set_ylabel('Offshore V (m/s)')
axes[3].legend(bbox_to_anchor=(0.90, 1), loc="upper left")

axes[3].set_xlabel('Date')

plt.show()
# fig.savefig('//srv-ott3.baird.com/Projects/13539.101 L\'Ansecoy Bay, Mustique/06_Models/01_MIKE3/00_Figures/' +
#             '/uVel_TS.png', bbox_inches='tight')

# %% Plotting
# Shaded Water
mapbox = 'https://api.mapbox.com/styles/v1/alexander0042/ckemxgtk51fgp19nybfmdcb1e/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiYWxleGFuZGVyMDA0MiIsImEiOiJjazVmdG4zbncwMHY4M2VrcThwZGUzZDFhIn0.w6oDHoo1eCeRlSBpwzwVtw'
x, y, arrow_length = 0.93, 0.95, 0.12
fontprops = fm.FontProperties(size=12)
modelPlot = range(6, 7)

vmin = 0
vmax = 1
scale = 1  # 5

for m in modelPlot:
    if m < 4 or m == 6:
        vmax = 5
        qmax = 4
        scale = 50
        amin = 1
    else:
        vmax = 1
        qmax = 0.25
        scale = 75
        amin = 3

    fig, axes = plt.subplots(figsize=(8, 8))

    # Convert to feet and ignore missing
    cur_plot = curSpeed_list[m] * 3.28084
    cur_nan = np.isnan(cur_plot)

    axDHI = dfs_list[m].plot(cur_plot[~cur_nan], plot_type='contourf', show_mesh=False, cmap='viridis', ax=axes,
                             levels=11,
                             vmin=vmin, vmax=vmax, label='Current Speed (ft/s)',
                             elements=dfs_list[m].element_ids[~cur_nan])

    # Plot arrows on overset grid
    overGrid = dfs_list[m].get_overset_grid(dx=50)
    interpolant = dfs_list[m].get_2d_interpolant(overGrid.xy, n_nearest=1)

    # Interpolate velocity at last time step by selecting time from dataset
    overGrid_Cur = dfs_list[m].interp2d(ds_list[m][ds_list[m].time[-1]:], *interpolant,
                                        shape=(overGrid.ny, overGrid.nx))

    overGrid_U = overGrid_Cur["U velocity"][-1]
    overGrid_V = overGrid_Cur["V velocity"][-1]

    # Normalize velocity above limit
    overGrid_U_Scale = overGrid_U * 3.28084
    overGrid_V_Scale = overGrid_V * 3.28084

    r = np.power(np.add(np.power(overGrid_U_Scale, 2), np.power(overGrid_V_Scale, 2)), 0.5)
    curPlotMask = np.sqrt((overGrid_U_Scale) ** 2 + (overGrid_V_Scale) ** 2) > qmax

    overGrid_U_Plot = np.zeros(overGrid_U_Scale.shape)
    overGrid_V_Plot = np.zeros(overGrid_V_Scale.shape)

    # Normalize arrows to 1
    overGrid_U_Plot = overGrid_U_Scale / r
    overGrid_V_Plot = overGrid_V_Scale / r

    # Scale arrows below qmax
    overGrid_U_Plot[~curPlotMask] = overGrid_U_Plot[~curPlotMask] * (r[~curPlotMask] / qmax)
    overGrid_V_Plot[~curPlotMask] = overGrid_V_Plot[~curPlotMask] * (r[~curPlotMask] / qmax)

    qv = axDHI.quiver(overGrid.x, overGrid.y, overGrid_U_Plot, overGrid_V_Plot, scale=scale,
                      color='k', headlength=3.5, headwidth=3.5, headaxislength=3.5, width=0.0015, minlength=amin)  # 200

    axes.set_xlim(left=427800, right=431000)
    axes.set_ylim(bottom=4758000, top=4762000)

    ctx.add_basemap(axes, source=mapbox, crs='EPSG:32616')
    # axes.title.set_text(runLog['Short Description'][m])
    # axes.titlesize = 'x-large'
    fig.suptitle(runLog['Short Description'][m], fontsize=18)
    axes.set_xlabel('Easting [m]')
    axes.set_ylabel('Northing [m]')

    plt.show()

    fig.savefig(
        '//srv-mad3.baird.com/Projects/13632.101 South Shore Breakwater/06_Models/04_MIKE21_HD/Images/Production/' +
        runLog['Short Description'][m] + '_RevC_Current.png', bbox_inches='tight', dpi=300)

# %% Plot Bathymetry

fig, axes = plt.subplots(figsize=(8, 8))
# Convert to feet and ignore missing
bed_plot = (bed_list[m] * 3.28084) - 578.007
bed_nan = np.isnan(bed_plot)

axDHI = dfs_list[m].plot(bed_plot[~bed_nan], plot_type='contourf', show_mesh=False, cmap='magma_r', ax=axes, levels=9,
                         vmin=-80, vmax=0, label='Bed Elevation (ft)',
                         elements=dfs_list[m].element_ids[~bed_nan])

axes.set_xlim(left=427800, right=431000)
axes.set_ylim(bottom=4758000, top=4762500)

ctx.add_basemap(axes, source=mapbox, crs='EPSG:32616')

fig.suptitle('Bed Elevation', fontsize=18)
axes.set_xlabel('Easting [m]')
axes.set_ylabel('Northing [m]')

plt.show()

fig.savefig(
    '//srv-mad3/Projects/13632.101 South Shore Breakwater/10_Reports&Pres/13632.101.R3 Ph I BOD/Support files/' +
    'Bed_Elevation.png', bbox_inches='tight', dpi=300)

# %% Read time series
MIKEds_list = [None] * (max(modelPlot) + 1)
MIKEdsT_list = [None] * (max(modelPlot) + 1)

for m in modelPlot:
    dfsIN = Dfs0(pl.Path(runLog['Run Location'][m], str(runLog['Number'][m]) + '_' +
                         runLog['Run Name'][m] + '.sw - Result Files', 'BreakPts.dfs0').as_posix())
    dfsIN_read = dfsIN.read()
    MIKEds_list[m] = dfsIN_read.to_dataframe()

    dfsTIN = Dfs0(pl.Path(runLog['Run Location'][m], str(runLog['Number'][m]) + '_' +
                          runLog['Run Name'][m] + '.sw - Result Files', 'TransectPTS.dfs0').as_posix())
    dfsTIN_read = dfsTIN.read()
    MIKEdsT_list[m] = dfsTIN_read.to_dataframe()

    # Cleanup unnecessary variables
    del dfsIN_read
    del dfsIN
    del dfsTIN_read
    del dfsTIN

# %% Read in Toe and Crest Shapefiles
breakwaterPTS = gp.read_file("//srv-mad3.baird.com/Projects/"
                             "13632.101 South Shore Breakwater/08_CADD/Outgoing/"
                             "20211211_Toe Extents (to Alexander)/"
                             "20211211_Toe_Extents_NAD83_WISStatePlaneSZn_USFt_Lines_OffshoreClipSimple_10m_vertexUTM.shp")
breakCrest = pd.read_csv(
    '//srv-mad3.baird.com/Projects/13632.101 South Shore Breakwater/08_CADD/Outgoing/20211214_Crest Points (to Alexander)/20211214_Crest_Points_m.csv',
    header=None, names=['x', 'y', 'z'])
breakCrest_gdf = gp.GeoDataFrame(breakCrest, crs='EPSG:32154',
                                 geometry=gp.points_from_xy(breakCrest.x, breakCrest.y))
breakCrest_gdf.to_crs('EPSG:32616', inplace=True)

breakwaterPTS_Crest = breakwaterPTS.sjoin_nearest(breakCrest_gdf)
breakwaterPTS_Crest.rename(columns={'x': 'breakCrest_x', 'y': 'breakCrest_y', 'z': 'Crest'}, inplace=True)

# %% Merge with data
breakPointsOut = [None] * (max(modelPlot) + 1)
breakTimesOut = [None] * (max(modelPlot) + 1)

for m in modelPlot:
    breakwaterPTS_times = None

    for t in range(0, MIKEds_list[m].shape[0]):
        breakwaterPTS_merge = None
        breakwaterPTS_merge = breakwaterPTS_Crest

        for i in range(0, MIKEds_list[m].shape[1]):
            paramName = MIKEds_list[m].columns.values[i][MIKEds_list[m].columns.values[i].find('"', 5, -1) + 3:]
            if paramName not in breakwaterPTS_merge.columns:
                breakwaterPTS_merge[paramName] = np.full([breakwaterPTS_merge.shape[0], 1], np.nan)
            tmpFID = int(MIKEds_list[m].columns.values[i][1:MIKEds_list[m].columns.values[i].find('"', 1)])
            tmpIND = int(MIKEds_list[m].columns.values[i][5:MIKEds_list[m].columns.values[i].find('"', 5)])

            breakwaterPTS_merge.loc[((breakwaterPTS_merge.FID == tmpFID) &
                                     (breakwaterPTS_merge.vertex_ind == tmpIND)),
                                    paramName] = MIKEds_list[m].iloc[t, i]

        breakwaterPTS_merge['Time'] = MIKEds_list[m].index[t]

        breakwaterPTS_times = pd.concat([breakwaterPTS_times, breakwaterPTS_merge], ignore_index=True)

    breakTimesOut[m] = breakwaterPTS_times

# %% Read in Breakwater Transect Points Sh
breakwaterT = pd.read_csv("C:/Users/arey/files/Projects/SouthShore/Bathy/BreakTransectPTS_Names.csv", sep='\t')

breakwaterT_PTS = gp.GeoDataFrame(breakwaterT, geometry=gp.points_from_xy(breakwaterT.X, breakwaterT.Y),
                                  crs='EPSG:32616')

# %% Merge with data
breakPoints_TOut = [None] * (max(modelPlot) + 1)
breakTimes_TOut = [None] * (max(modelPlot) + 1)

for m in modelPlot:
    breakwaterPTS_times = None

    for t in range(0, MIKEdsT_list[m].shape[0]):
        breakwaterPTS_merge = None
        breakwaterPTS_merge = breakwaterT_PTS

        for i in range(0, MIKEdsT_list[m].shape[1]):
            paramName = MIKEdsT_list[m].columns.values[i][MIKEdsT_list[m].columns.values[i].find(':', 5, -1) + 2:]
            if paramName not in breakwaterPTS_merge.columns:
                breakwaterPTS_merge[paramName] = np.full([breakwaterPTS_merge.shape[0], 1], np.nan)
            tmpName = MIKEdsT_list[m].columns.values[i][0:MIKEdsT_list[m].columns.values[i].find(':', 1)]

            breakwaterPTS_merge.loc[(breakwaterPTS_merge.Name == tmpName),
                                    paramName] = MIKEdsT_list[m].iloc[t, i]

        breakwaterPTS_merge['Time'] = MIKEdsT_list[m].index[t]

        breakwaterPTS_times = pd.concat([breakwaterPTS_times, breakwaterPTS_merge], ignore_index=True)

    breakTimes_TOut[m] = breakwaterPTS_times

# %% Format and save

for m in modelPlot:
    saveTmp = breakTimesOut[m].copy()
    saveTmp['X'] = saveTmp.geometry.x
    saveTmp['Y'] = saveTmp.geometry.y
    saveTmp.drop(['vertex_par', 'vertex_p_1', 'angle', 'geometry', 'index_right',
                  'breakCrest_x', 'breakCrest_y', 'Length'], axis=1, inplace=True)
    saveTmp.sort_values(by=['FID', 'vertex_ind'], inplace=True, ignore_index=True)

    # Reorder columns
    colNames = saveTmp.columns.values
    saveTmp = saveTmp[['X', 'Y', *colNames[0:-2]]]
    saveTmpT = saveTmp.transpose(copy=True)

    # Transect points
    saveTmp2 = breakTimes_TOut[m].copy()
    saveTmp2.drop(['geometry'], axis=1, inplace=True)
    saveTmp2T = saveTmp2.transpose(copy=True)

    saveTmpT.to_csv('//srv-mad3.baird.com/Projects/13632.101 South Shore Breakwater/06_Models/02_Mike21SW/Results/' +
                    'Toe' + runLog['Short Description'][m] + '.csv')

    saveTmp2T.to_csv('//srv-mad3.baird.com/Projects/13632.101 South Shore Breakwater/06_Models/02_Mike21SW/Results/' +
                     'Transect' + runLog['Short Description'][m] + '.csv')
