######################################################################
#             / ____|  ____|  __ \| |  | |  ____|  ____|             #
#            | |    | |__  | |__) | |__| | |__  | |__                #
#            | |    |  __| |  ___/|  __  |  __| |  __|               #
#            | |____| |____| |    | |  | | |____| |____              #
#             \_____|______|_|    |_|  |_|______|______|             #
######################################################################
#
# CEPHEE
# Copyright (C) 2024 Toulouse INP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details :
# <http://www.gnu.org/licenses/>.
#
######################################################################

from qgis.PyQt.QtCore import pyqtSignal
from qgis.PyQt.QtWidgets import QDockWidget, QFileDialog
from qgis.core import (QgsVectorLayer, QgsRasterLayer,QgsProject, QgsMapLayerProxyModel, QgsMessageLog, Qgis, QgsTask,
                       QgsApplication, QgsCoordinateReferenceSystem)
from .ui.Ui_BathymetricWidget import Ui_BathymetricWidget
from ..core.Hydraulics import *
from ..core.Bathymetrics  import *
from os import path

class BathymetricWidget(QDockWidget, Ui_BathymetricWidget):

    closingWidget = pyqtSignal(name="closingWidget")

    def __init__(self, iface, BV, param, parent = None):
        super(BathymetricWidget, self).__init__(parent)
        self.setupUi(self)
        self.iface = iface
        self.BV = BV
        self.param = param
        self.pushButton_compute.clicked.connect(self.compute)
        self.radioButton_fromDischarge.toggled.connect(self.updatePanel)
        self.comboBox_bankLayerSelection.setFilters(QgsMapLayerProxyModel.VectorLayer)

    def closeEvent(self, event):
        self.closingWidget.emit()
        event.accept()

    def ui_to_param(self):
        self.param['H']['outletDischarge'] = float(self.lineEdit_outletDischarge.text())
        self.param['H']['dischargeMethod'] = self.comboBox_dischargeMethod.currentText()
        if self.radioButton_fromDischarge.isChecked():
            self.param['B']['fromQ'] = True
        elif self.radioButton_fromWaterDepth.isChecked():
            self.param['B']['fromQ'] = False
        self.param['B']['depth'] = float(self.lineEdit_waterDepth.text())

        self.param['B']['bathymetricSections'] = self.comboBox_bathymetricSections.currentText()
        if self.comboBox_bathymetricSections.currentText() == "rectangular":
            self.param['B']['bathymetricSections'] = "Rectangular"
        elif self.comboBox_bathymetricSections.currentText() == "parabolic":
            self.param['B']['bathymetricSections'] = "Parabolic"
        elif self.comboBox_bathymetricSections.currentText() == "triangular":
            self.param['B']['bathymetricSections'] = "Triangular"
        elif self.comboBox_bathymetricSections.currentText() == "imported sections":
            self.param['B']['bathymetricSections'] = "Original"

        self.param['B']['riverbanks_filepath'] = self.comboBox_bankLayerSelection.currentLayer().dataProvider().dataSourceUri()
        self.param['B']['smoothSlope'] = self.checkBox_smoothSlope.isChecked()
        self.param['B']['mapping_method'] = self.comboBox_mappingMethod.currentText()
        self.param['B']['output_resolution'] = float(self.lineEdit_outputResolution.text())

    def updatePanel(self):
        if self.radioButton_fromDischarge.isChecked():
            self.lineEdit_outletDischarge.setEnabled(True)
            self.comboBox_dischargeMethod.setEnabled(True)
            self.lineEdit_waterDepth.setDisabled(True)
        elif self.radioButton_fromWaterDepth.isChecked():
            self.lineEdit_outletDischarge.setDisabled(True)
            self.comboBox_dischargeMethod.setDisabled(True)
            self.lineEdit_waterDepth.setEnabled(True)

    def compute(self):
        self.ui_to_param()
        self.task = BackgroundProcess('process_bathymetric', self.BV, self.param)
        QgsApplication.taskManager().addTask(self.task)

class BackgroundProcess(QgsTask):

    def __init__(self, description, BV, param):
        super().__init__(description, QgsTask.CanCancel)
        self.BV = BV
        self.param = param

    def run(self):
        QgsMessageLog.logMessage(message="Starting bathymetric computation", tag="CEPHEE", level=Qgis.MessageLevel.Info)
        if self.param['B']['fromQ']:
            addQtoSection(self.BV, self.param)

        import_banks_from_layer(self.BV, self.param, self.param['B']['riverbanks_filepath'])
        self.BV.display('banks file imported, banks attributed to sections')
        drag_all_XS(self.BV, self.param)  # create the line of each section with the points of the banks

        if self.param['B']['mapping_method'] == 'interpolation':
            interpolate_DEM_channel(self.BV, self.param)
        elif self.param['B']['mapping_method'] == 'by_polygon':
            rasterize_DEM_channel(self.BV, self.param)
        dem_layer = QgsRasterLayer(path.join(self.param.work_path, 'global_channel_DEM.tif'), "global_channel_DEM")
        QgsProject.instance().addMapLayer(dem_layer)
        MergeRaster_channel_DEM(self.BV, self.param.work_path)

        QgsMessageLog.logMessage(message="New DEM created", tag="CEPHEE", level=Qgis.MessageLevel.Info)
        return True





