######################################################################
#             / ____|  ____|  __ \| |  | |  ____|  ____|             #
#            | |    | |__  | |__) | |__| | |__  | |__                #
#            | |    |  __| |  ___/|  __  |  __| |  __|               #
#            | |____| |____| |    | |  | | |____| |____              #
#             \_____|______|_|    |_|  |_|______|______|             #
######################################################################
#
# 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/>.
#
######################################################################

# global
from qgis.PyQt.QtWidgets import QWidget
from qgis.PyQt.QtCore import pyqtSignal
from qgis.core import QgsMapLayerProxyModel
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT
from shapely.geometry import LineString
import numpy as np

# local
from .ui.Ui_PlotWidget import Ui_PlotWidget
from ..core.Tools import compute_distance


class PlotWidget(QWidget, Ui_PlotWidget):
    closingWidget = pyqtSignal(name="closingWidget")

    def __init__(self, iface, BV, param, parent=None):
        self.iface = iface
        self.BV = BV
        self.param = param
        super(PlotWidget, self).__init__(parent)
        self.setupUi(self)
        self.figureFrame.resize(632, 564)
        self.figureWidget.__init__(BV, parent=self.figureFrame)
        self.nav_toolbar = NavigationToolbar2QT(self.figureWidget, self)
        self.nav_toolbar.removeAction(self.nav_toolbar.actions()[0])
        self.verticalLayout.insertWidget(10, self.nav_toolbar)
        self.comboBox_layerSelection.setFilters(QgsMapLayerProxyModel.VectorLayer)
        self.comboBox_layerSelection.currentIndexChanged.connect(self.layerSelected)
        self.layerSelected()
        self.pushButton_plot_qgis.clicked.connect(self.plot_qgis)
        self.update_reach_list()
        self.comboBox_reachSelection.currentIndexChanged.connect(self.update_cephee_panel)
        self.checkBox_plotXS.stateChanged.connect(self.update_cephee_panel)
        self.pushButton_plot_cephee.clicked.connect(self.plot_cephee)

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

    def resizeEvent(self, event):
        self.figureWidget.resize(self.figureFrame.size().width(), self.figureFrame.size().height())

    # QGIS tab
    def layerSelected(self):
        if self.comboBox_layerSelection.currentLayer():
            self.label_nID.setText("0-" + str(len(self.comboBox_layerSelection.currentLayer()) - 1))

    def plot_qgis(self):
        map_layer = self.comboBox_layerSelection.currentLayer()
        id_section = int(self.lineEdit_XS_qgis.text())
        self.figureWidget.plot_qgis(map_layer, id_section)

    # CEPHEE tab
    def update_reach_list(self):
        self.comboBox_reachSelection.clear()
        if len(self.BV.reach) > 0:
            for i in range(len(self.BV.reach)):
                self.comboBox_reachSelection.addItem(self.BV.reach[i].name)
                print(self.BV.reach[i].name)
        else:
            self.comboBox_reachSelection.addItem('no reach available')

    def update_cephee_panel(self):
        self.lineEdit_XS_cephee.clear()
        if self.checkBox_plotXS.isChecked():
            self.lineEdit_XS_cephee.setEnabled(True)
            self.comboBox_fieldSelection.setEnabled(True)
            self.checkBox_zCenterline.setDisabled(True)
        else:
            self.lineEdit_XS_cephee.setDisabled(True)
            self.comboBox_fieldSelection.setDisabled(True)
            self.checkBox_zCenterline.setEnabled(True)
        n_sections = "-"
        if len(self.BV.reach):
            current_reach = self.BV.reach[self.comboBox_reachSelection.currentIndex()]
            if len(current_reach.section_list) > 0:
                n_sections = (str(current_reach.id_first_section) + "-"
                              + str(current_reach.id_first_section + len(current_reach.section_list) - 1))
                self.lineEdit_XS_cephee.setText("0")
        self.label_nSections.setText(n_sections)

    def plot_cephee(self):
        id_reach = self.comboBox_reachSelection.currentIndex()
        if self.comboBox_reachSelection.currentText() == "no reach available":
            return

        self.figureWidget.axes.cla()

        if self.checkBox_plotXS.isChecked():
            # Select cross-section
            id_section = int(self.lineEdit_XS_cephee.text()) - self.BV.reach[id_reach].id_first_section
            if id_section < 0 or id_section >= len(self.BV.reach[id_reach].section_list):
                self.BV.display('Selected section out of range', 1)
                return
            section = self.BV.reach[id_reach].section_list[id_section]

            # filter using banks
            X = section.coord.array['Xt']
            if section.bank:
                id_start = np.where(X >= section.bank[0][0])[0][0]
                if id_start > 0:
                    id_start = id_start - 1
                id_end = np.where(X >= section.bank[0][1])[0][0]
            else:
                id_start = 0
                id_end = len(X)

            # select and plot field
            id_field = self.comboBox_fieldSelection.currentIndex()
            if id_field == 0:
                self.figureWidget.plot(X[id_start:id_end], section.coord.values['B'][id_start:id_end], c='black')
                if section.WSE:
                    self.figureWidget.plot_uniform(X[id_start:id_end], section.WSE, c='blue')
            elif id_field == 1:
                self.figureWidget.plot(X[id_start:id_end], section.coord.values['U'][id_start:id_end], c='red')
            elif id_field == 2:
                self.figureWidget.plot(X[id_start:id_end], section.coord.values['H'][id_start:id_end], c='green')


        else:

            c_reach = self.BV.reach[id_reach]
            # create line with z min of section
            X_bed = [c_reach.section_list[i].centre.x for i in range(len(c_reach.section_list))]
            Y_bed = [c_reach.section_list[i].centre.y for i in range(len(c_reach.section_list))]
            Z_bed = [c_reach.section_list[idpoint].Zbed for idpoint in range(len(c_reach.section_list))]
            line_bed = LineString([(x, y, z) for x, y, z in zip(X_bed, Y_bed, Z_bed)])

            self.figureWidget.plot_z(c_reach.Xinterp, line_bed)

            if self.checkBox_zCenterline.isChecked():
                distance = compute_distance(c_reach.geodata['geometry'].coords)
                self.figureWidget.plot_z_origin(distance, c_reach.geodata['geometry'])

            if c_reach.section_list[0].WSE > 0:
                WS = []
                for j in range(0, len(c_reach.section_list)):
                    WS.append(c_reach.section_list[j].WSE)
                self.figureWidget.plot_WS(c_reach.Xinterp, WS)
