 # -*- coding: utf-8 -*-
"""
Created on Wed Aug 23 07:56:23 2023

@author: lcassan
"""

from os import getcwd, path
import sys
sys.path.append(path.join(getcwd(), "thirdparty"))
import time
import argparse

from core.Data import *
from core.Bathymetrics import *
from core.postCEPHEE import *
from core.Parameters import read_param

hydro_lib = None
'''
try:
    import pysheds
    computeGlobal_avail = True
    hydro_lib='pysheds'
except ImportError:
    computeGlobal_avail = False

try:
    import pyflwdir
    computeGlobal_avail = True
    hydro_lib = 'pyflwdir'
except ImportError:
    computeGlobal_avail = False

'''

def only_banks(params,  mesh_size):


    #if computeGlobal_avail == False:
    params['C']['computeGlobal'] = False

    #--------DATA process-------
    BV1 = ModelCatchment(qgis_mode=False)

    # -----------------------------------------------------------------------------
    # Reading topographic data
    init_DEM_and_network(BV1, params,hydro_lib)
    BV1.display('DEM and Network initialized', 0)

# -----------------------------------------------------------------------------
    # Traitement du reséau pour le mettre au standard hydraulique 'utilisable par un code 1D)
    nreach = 0
    new_hydro = gpd.GeoDataFrame(columns=BV1.hydro_network.columns, crs=BV1.crs)
    for i, row in BV1.hydro_network.iterrows():
        line = row['geometry']
        line_with_z = LineString([(x, y, 0) for x, y in zip(line.xy[0], line.xy[1])])
        cline_bound0 = line_with_z.boundary.geoms[0]
        cline_bound1 = line_with_z.boundary.geoms[1]
        if BV1.outlet_point:
            if cline_bound0.distance(BV1.outlet_point) < cline_bound1.distance(BV1.outlet_point):
                line_with_z = LineString(list(line_with_z.coords)[::-1])
        if line_with_z.length > 5000:
            new_hydro.loc[nreach] =row
            new_hydro.loc[nreach, 'geometry'] = line_with_z
            nreach +=1

    BV1.hydro_network = new_hydro
    BV1.ordered_network = new_hydro
    BV1.ordered_network['River'] = BV1.ordered_network['gid']
    new_reach =[]
    BV_global = ModelCatchment(qgis_mode=False)
    BV_global.ordered_network = BV1.ordered_network  # on fait un BV global pour appliquer remove_XS

    for i in range(len(BV1.ordered_network)):
        print(i)
        # on change l'exutoire pour chaque bief
        BV1.list_of_outlet = [[BV1.ordered_network.loc[i, 'River'], [BV1.ordered_network.loc[i, 'River']], 0]]
        BV1.createReach()
        BV1.interpolateReach(params['XS']['creation_step'] )
        params['XS']['distSearchMin'] = 0
        create_XS_lines(BV1, params, 'mesh')
        #optimize_XS_lines(BV, param)
        project_XS_lines(BV1, params)
        BV1.compute_slope(params['N']['npoly'])
        impose_water_depth(BV1, params)
        reduceXStobank(BV1, params['XS']['distSearchMin'], 'channel')

        if len(BV1.reach[0].section_list) > 3:
            BV1.reach[0].create_bank_lines()
            new_reach.append(BV1.reach[0])

    BV_global.reach= new_reach
    remove_crossing_XS(BV_global)
    createAllBankLines(BV_global)
    save_bank_lines(BV_global, params.work_path, 'all_banks')
    BV_global.display("Bank lines created")
    return  os.path.join(params.work_path,'banks_lines_all_banks.shp')

if __name__ == '__main__':
    # Execute when the module is not initialized from an import statement.
    # CLI argument parser
    parser = argparse.ArgumentParser(description='a CLI (command line interface) for CEPHEE')
    parser.add_argument('parameter_file', help='Provide parameter file',default=os.path.join(getcwd(),'core/Parameters.py'))
    parser.add_argument('--mesh_size', help='minimal mesh size expected', default=None)
    args = parser.parse_args()


    # read input files
    if not path.isfile(args.parameter_file):
        raise SystemExit(args.parameter_file + ' file not found')

    params = read_param(args.parameter_file)
    mesh_size = np.float32(args.mesh_size)
    BV = only_banks(params,mesh_size)

