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

@author: lcassan
"""

from os import getcwd, path
import time
import argparse
import rioxarray as rxr
import pickle
import geopandas as gpd
from core.Data import *
from core.CrossSection import *
from core.postCEPHEE import *
import datetime
from cephee_cli import cephee_cli
from core.Parameters import read_param
from core.Hydraulics import select_computation, createAllBankLines, save_bank_lines
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

'''
Exemple de fichier CLI permettant de mapper une serie d'image satellite sur un MNT

'''

def map_image_series(params,image_folder,model):

    params['H']['createBanks'] = False
    params['H']['hydraulicCurve'] = False
    BV = cephee_cli(params, model = model)
    flist = sorted(glob.glob((os.path.join(image_folder, '*' + '.tif'))))

    for ifile,file in enumerate(flist):
        path, filename = os.path.split(file)
        print(filename)
        FML_acquisition_time = filename[24:39]
        params.verbose = True
        DEM_file = '/Users/cassan/PycharmProjects/cephee/tmp/tonneins/DEM/merged_2023_v2_culvert.tif'

        params['I']['riverbanks_filepath'] = file
        params['H']['levee'] = False
        BV_fromMask(BV, params)
        DEMi = rasterio.open(BV.DEM_stack['file_list'][0], 'r', crs=BV.crs)
        for reach in BV.reach:
            for j, section in enumerate(reach.section_list):
                _, bank = XSbounds(section.geom, BV.outline, section.centre.x, section.centre.y,
                                      params['XS']['method_banks'])
                section.bank = bank

                WSE0 = projOnDEM([bank[1][0].x],[bank[1][0].y],DEMi)
                WSE1 = projOnDEM([bank[1][1].x], [bank[1][1].y],DEMi)
                section.WSE = np.nanmax([WSE0, WSE1])#(WSE0 + WSE1) / 2

        params['H']['createBanksMethods'] = 'WSE'
        BV.compute_slope(npoly=6, data='bed') #lissage de la pente du fond
        BV.compute_slope(npoly=6, data='WSE') #lissage de la pente de surface libre

        BV, config_cal = select_computation(BV, params)
        config_cal = config_cal + FML_acquisition_time
        createAllBankLines(BV)
        save_bank_lines(BV, params.work_path, config_cal)
        export_map(BV, params, config_cal)


def roundTime(dt=None, dateDelta=datetime.timedelta(minutes=1)):
    """Round a datetime object to a multiple of a timedelta
    dt : datetime.datetime object, default now.
    dateDelta : timedelta object, we round to a multiple of this, default 1 minute.
    Author: Thierry Husson 2012 - Use it as you want but don't blame me.
            Stijn Nevens 2014 - Changed to use only datetime objects as variables
    """
    roundTo = dateDelta.total_seconds()

    if dt == None: dt = datetime.datetime.now()
    seconds = (dt - dt.min).seconds
    rounding = (seconds + roundTo / 2) // roundTo * roundTo
    return dt + datetime.timedelta(0, rounding - seconds, -dt.microsecond)



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('image_folder', help='Specify folder for output files', default=getcwd())
    parser.add_argument('--model', help='model catchment to use', 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)
    map_image_series(params,args.image_folder,args.model)




