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

@author: lcassan
"""

from os import getcwd, path
import time
import argparse

from core.postCEPHEE import *
from core.ModelCatchment import ModelCatchment
from core.Tools import *
from core.Hydraulics import *
from core.CrossSection import *
from core.Data import *
from core.Bathymetrics import *
from shapely.geometry import Point
from shapely.geometry import LineString
from core.Parameters import Parameters
import importlib
'''
Exemple de fichier CLI permettant un creusement du lit pour un seul tronçon
Les paramètres suivant doivent avoir des valeurs spécifiques correspondant à une cohérence physique
params['C']['ComputeGlobal']= False
params['H']['dischargeMethod']=  Constant
Le lit minieur est creusé et foruni sous la forme d'un raster à la résolution params['H']['dxlat]

Le merge avec le MNT initial est à faire par l'utilisateur soit avec Qgis soit avec la fonction only_merge

'''

# CLI argument parser
parser = argparse.ArgumentParser(description='a CLI (command line interface) for CEPHEE')
parser.add_argument('parameter_file', help='Provide parameter file')
parser.add_argument('--output_folder', help='Specify folder for output files', default=getcwd())
args = parser.parse_args()

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

# Créer un dictionnaire pour stocker les variables et classes définies dans le fichier
name= {}
# Ouvrir et lire le fichier Python
with open(args.parameter_file, "r") as file:
    code = file.read()
# Exécuter le contenu du fichier dans le namespace
exec(code,name)
Param = name.get('Parameters')
params =Param()

#Force certains paramètres à avoir un sens physique pour ce workflow (un seul tronçon, pas de MNT)
params['H']['dischargeMethod']= 'Constant'
params['C']['findCatchment'] = False
params['C']['computeGlobal'] = False
params['B']['interpolationMethod'] = params['H']['createBanksMethods']
if params['XS']['creation_step'] <= params['XS']['interpolation_step']:
    params['XS']['interpolate_XS'] = False

riverbanks_filepath =params['B']['riverbanks_filepath']

if riverbanks_filepath == None:
    print('No bank lines used')

if params['B']['useImportedSections']:
    choice_XS = 'Imported'
    XS_filepath =params['XS']['XS_filepath']
    print('Field bathymetry used :' + XS_filepath)
else:
    choice_XS = 'New'
    average_slope = params['B']['average_slope']
    params['H']['createBanksMethods'] = 'Obs'
    params['B']['interpolationMethod'] = 'Obs'
    params['XS']['distSearchMin'] = 0
    print('creation of new river with slope :' + str(average_slope))



#-----------------------------------------------------------------------------
#instanciation du modèle
BV1=ModelCatchment()

#-----------------------------------------------------------------------------
#lecture des données topo
BV1.read_network(river_filename = params['N']['network_filepath'],nclassemax=3)
BV1.ordered_network = BV1.hydro_network
print('Network read')

BV1.ordered_network['River'] = BV1.ordered_network['gid']
BV1.ordered_network.loc[0,'Reach']=0
BV1.list_of_outlet = [[BV1.ordered_network.loc[0,'River'],[BV1.ordered_network.loc[0,'gid']],0]]
BV1.createReach()

if choice_XS == 'Imported':
    importXSlines(BV1, params, XS_filepath=XS_filepath)
    print('Cross section imported')
else:
     #le point central est forcement sur la centerline
    BV1.interpolateReach(params['XS']['creation_step'])  # interpole les tronçons de la distance fournit en argument
    createXSlines(BV1, params['XS']['width'], params['XS']['number_of_points'])
    for ids, section in enumerate(BV1.reach[0].section):
        section.originXSLocation(params['XS']['originSection'], params['XS']['distSearchMin'])  # l'origine de la distance latérale est au point le plus bas
    print('Cross section created')

if not params['B']['useImportedSections']:
    BV1.reach[0].slope =[]
    for ids, section in enumerate(BV1.reach[0].section):
        BV1.reach[0].slope.append(average_slope)
        section.slope = average_slope

if params['XS']['interpolate_XS']:
    params['XS']['distSearchMin'] = 0
    interpolate_XS_lines(BV1,params)
    print('Section interpolated')

XS_lines_filepath = os.path.join(params.work_path, 'XS_lines_interp.shp')
saveXSlines(BV1, XS_lines_filepath)

if params['B']['fromQ'] and params['H']['createBanksMethods'] == 'Obs':
    addQtoSection(BV1, params)
setConstantFriction(BV1, params['H']['frictionValue'])

if choice_XS == 'Imported':
    if params['H']['createBanksMethods'] == 'Normal':
        Q_outlet = addQtoSection(BV1,params)
        computeNormalAndCriticalDepth(BV1,params)
    elif params['H']['createBanksMethods'] == '1D':
        addQtoSection(BV1, params)
        backWaterProfile(BV1, params)
    elif params['H']['createBanksMethods'] == 'Himposed':
        addQtoSection(BV1, params)
        impose_water_depth(BV1, params)


if riverbanks_filepath == None:# and not choice_XS =='Imported':
    bank_to_edge_end(BV1, params)

#---modification de la bathymetry---------------------------------------------
#-----------------------------------------------------------------------------
drag_all_XS(BV1, params, type_comp=params['B']['interpolationMethod'],riverbanks_filepath = riverbanks_filepath)  # create the line of each section with the points of the banks
if params['H']['mapping_method'] == 'interpolation':
    interpolate_DEM_channel(BV1, params)
else:
    rasterize_DEM_channel(BV1, params)


createAllBankLines(BV1, resultType=params['H']['createBanksMethods'])
save_bank_lines(BV1, params.work_path)

