#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 15:09:57 2021

@authors: Antoine Lucas, <lucas@ipgp.fr>

@purpose: Lib linked to the Shaltop shallow water model version 2020
    This library is a direct convertion from the initial matlab package developped over the 2006--2014 period. The design is purposly object-oriented for making any futher development as easier as possible.

@Disclamer: this lib should work with previous version outputs, but some modification might be required accordingly to some recent changes.



MIT License, Copyright (c) 2021 Antoine Lucas

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

class svshClass:
    params = None
    Z = None
    R = None
    u = None
    v = None
    fx = None
    fy = None
    ota = None
    Dir = None
    time = None


class paramsClass:
    filename = ''
    nx = None
    ny = None
    dx = None
    dy = None
    x = None
    y = None
    tmax = None
    g = None
    icomp = None
    nbIm = None
    delta1 = None
    delta2 = None
    delta3 = None
    delta4 = None
    theta0 = None
    theta1 = None
    beta = None
    diam = None
    wlong = None


def getParam(filename):
    import numpy as np
    import os

    if os.path.isfile(filename):
        f = open(filename)
        pm = np.genfromtxt(filename)

        params = paramsClass()
        params.filename = filename
        params.nx = np.int32(pm[2,0])
        params.ny = np.int32(pm[2,1])
        params.dx = pm[3,0]
        params.dy = pm[3,1]
        params.ax = np.linspace(params.dx, params.dx*params.nx, num=params.nx)
        params.ay = np.linspace(params.dy, params.dy*params.ny, num=params.ny)
        params.nbIm = np.int32(pm[4,1])
        params.tmax = pm[12,0]
        params.g = pm[13,0]
        params.icomp = pm[5,0]
        params.delta1 = pm[6,0]*180.0/np.pi  #!!!!! from version 2020? the plotmat contains these angles in radians and not in derees as opposed to previous versions of shaltop !!!!!
        params.delta2 = pm[7,0]*180.0/np.pi
        params.delta3 = pm[8,0]*180.0/np.pi
        params.delta4 = pm[9,0]*180.0/np.pi
        params.theta0 = pm[10,0]
        params.theta1 = pm[11,0]
        params.beta = pm[14,0]
        params.diam = pm[14,1]
        params.wlong = pm[14,2]
        f.close()

        return params

    else:
        print(f'File {filename} is not accessible')

def readZ(zFile,params):
    import numpy as np

    dtype = np.dtype('f')
    try:
        with open(zFile, "rb") as f:
            numpy_data = np.fromfile(f,dtype)
            z = numpy_data.reshape(params.ny,params.nx)
            return z
    except IOError:
        print("!!! svsh_error !!!")
        print('Error While Opening the z file!')

def readOta(otaFile,params):
    import numpy as np

    dtype = np.dtype('f')
    try:
        with open(otaFile, "r") as f:
            numpy_data = np.loadtxt(f,dtype=dtype)
            ota = numpy_data.reshape(params.ny,params.nx)
            return ota
    except IOError:
        rint("!!! svsh_error !!!")
        print('Error While Opening the ota file!')



def iComp(i):
    switcher={
                1:'Coulomb (mu)',
                11:'Coulomb (muV*gamma)',
                2:'Pouliquen (exp(-hstop/dist))',
                21:'Pouliquen (With Froude number)',
                3:'Pouliquen (**power* (hstart - fricmain))',
                31:'Pouliquen 4 angles',
                32:'Pouliquen modified from Edwards, 2018',
                4:'Coulomb w/ filtering',
                5:'Coulomb friction + Bingham',
                6:'Bingham',
                7:'Mu(I)',
                8:'Voellmy',
                9:'Weakening'
             }
    return switcher.get(i,"Invalid rheology value")

def readbin(rFile,params):
    import numpy as np

    dtype = np.float32
    try:
        with open(rFile, "rb") as f:
            r = np.fromfile(f,dtype)
            t = len(r)/(params.nx*params.ny)
            

            if t.is_integer():
                r=np.reshape(r,(params.nx,params.ny,int(t)),order='F')
                r = r.transpose((1, 0, 2))
                return r
            else:
                print('Error While Opening the file. UNFINISHed writting?')

    except IOError:
        print('Error While Opening the file!')


def getSvsh(data2path):
    import numpy as np
    import os

    if os.path.isfile(data2path+'plotmat.dat'):
        params = getParam(data2path+'plotmat.dat')

        Z = readZ(data2path+"z.bin",params)
        R = readbin(data2path+"rho.bin",params)
        ota = readOta(data2path+"ota.d",params)
        svsh = svshClass()
        svsh.params = params
        svsh.Z = Z
        svsh.R = R
        svsh.ota = ota
        svsh.Dir = data2path
        svsh.time = np.linspace(0, svsh.params.tmax, num=svsh.params.nbIm).T
        return svsh

    else:
        print(f'File {filename} is not accessible')


def getInfoSvsh(svsh):
    print("Shaltop-2d simulation information:")
    print(" ")
    print(" |Directory:",svsh.params.filename)
    print(" |Problem size:",svsh.params.nx,'x',svsh.params.ny)
    print(" |Problem sampling:",svsh.params.dx,'x',svsh.params.dy)
    print(" |nb record :",int(svsh.params.nbIm))
    print(" |Tmax :",svsh.params.tmax)
    print(" |Reology: ",iComp(svsh.params.icomp))


def plotshZ(svsh):
    """
    plotshZ (svsh) makes a 3D plot of the shaded topography field.
    INPUT:
    ------
        @svsh: svsh structure

    OUTPUT:
    -------
        None

    """
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator
    from matplotlib.colors import LightSource
    import numpy as np

    X, Y = np.meshgrid(svsh.params.ax, svsh.params.ay)

    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))

    ls = LightSource(270, 45)

    rgb = ls.shade(svsh.Z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
    surf = ax.plot_surface(X,Y, svsh.Z, rstride=1, cstride=1, facecolors=rgb,
                       linewidth=0, antialiased=False, shade=False)
    ax.grid(False)
    plt.axis('off')
    plt.show()

def plotZ(svsh):
    """
	plotZ (svsh) makes a 3D plot of the topography field.
	INPUT:
	------
		@svsh: svsh structure

	OUTPUT:
	-------
		None

    """
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator

    import numpy as np


    fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

    X, Y = np.meshgrid(svsh.params.ax, svsh.params.ay)

    surf = ax.plot_surface(X,Y, svsh.Z,cmap=cm.gist_earth,
                       linewidth=0, antialiased=True)
    ax.grid(False)
    plt.axis('off')

    plt.show()


def plotDeposit(svsh,thresh=0):
    """
	plotDeposit (svsh,thresh=0) makes a 3D plot of the deposits over the topography.

	INPUT:
	------
		@svsh: svsh structure
        @thresh=0: threshold value for minimal value to display

	OUTPUT:
	-------
		None

    """
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator

    import numpy as np


    fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

    X, Y = np.meshgrid(svsh.params.ax, svsh.params.ay)
    D=svsh.R[:,:,-1]/svsh.ota # We want the final step, supposably being the deposits. And we crudely compensate for the slope angle. A more accurate approach would be to use the hzfree field and resample it over a regular grid. This might be part of future version.
    print("!!! svsh_warning :: plotDeposit function")
    print("For displaying the mass thicnknees, we crudely compensate for the slope angle. A more accurate approach would be to use the hzfree field and resample it over a regular grid. This might be part of future version.")
    Drgb = D.copy()
    Drgb[Drgb<=thresh]=0 #Thresh is the threshold for displaying the rho field
    Drgb = Drgb/np.quantile(D, 0.997)  # Some tricks for making usage of matplotlib
    Drgb[Drgb==0]=np.nan

    surf = ax.plot_surface(X,Y, svsh.Z+D,cmap=cm.bone,linewidth=0, antialiased=False,rstride=2, cstride=2)

    surf = ax.plot_surface(X,Y, svsh.Z+D,facecolors=plt.cm.magma(Drgb),cmap=cm.magma,linewidth=0, antialiased=False,rstride=2, cstride=2)
    cbar = plt.colorbar(surf, ticks=[0, 1])
    cbar.ax.set_yticklabels(['0', np.quantile(D, 0.997)])# Get rid of some potential outliers (in case of high curvature)
    cbar.set_label('Thickness [m]')

    ax.grid(False)
    plt.axis('off')

    plt.show()


def plotFlow(svsh,time,thresh=0):
    """
	plotDeposit (svsh,thresh=0) makes a 3D plot of the deposits over the topography.

	INPUT:
	------
		@svsh: svsh structure
        @time: a scaler or vector of integers indicating the index of desired steps
        @thresh=0: threshold value for minimal value to display

	OUTPUT:
	-------
		None

    """
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator

    import numpy as np
    print("!!! svsh_warning :: plotDeposit function")
    print("For displaying the mass thicnknees, we crudely compensate for the slope angle. A more accurate approach would be to use the hzfree field and resample it over a regular grid. This might be part of future version.")
    for ii in time:
        fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

        X, Y = np.meshgrid(svsh.params.ax, svsh.params.ay)

        D=svsh.R[:,:,ii]/svsh.ota # And we crudely compensate for the slope angle. A more accurate approach would be to use the hzfree field and resample it over a regular grid. This might be part of future version.

        Drgb = D.copy()
        Drgb[Drgb<=thresh]=0 #Thresh is the threshold for displaying the rho field
        Drgb = Drgb/np.quantile(D, 0.997)  # Some tricks for making usage of matplotlib
        Drgb[Drgb==0]=np.nan

        surf = ax.plot_surface(X,Y, svsh.Z+D,cmap=cm.bone,linewidth=0, antialiased=False,rstride=2, cstride=2)

        surf = ax.plot_surface(X,Y, svsh.Z+D,facecolors=plt.cm.magma(Drgb),cmap=cm.magma,linewidth=0, antialiased=False,rstride=2, cstride=2)
        cbar = plt.colorbar(surf, ticks=[0, 1])
        cbar.ax.set_yticklabels(['0', np.quantile(D, 0.997)])# Get rid of some potential outliers (in case of high curvature)
        cbar.set_label('Thickness [m]')
        timev = np.linspace(0, svsh.params.tmax, num=svsh.params.nbIm).T
        txtTitle = "Time: "+str(timev[ii])+" sec."
        plt.title(txtTitle)
        ax.grid(False)
        plt.axis('off')

        plt.show()
