# MainWindowTabInfo.py -- Pamhyr
# Copyright (C) 2024-2025  INRAE
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

import logging

from tools import timer, trace

from View.Tools.Plot.PamhyrToolbar import PamhyrPlotToolbar
from View.Tools.Plot.PamhyrCanvas import MplCanvas
from View.PlotXY import PlotXY
from View.Tools.PamhyrWidget import PamhyrWidget

from PyQt5.QtWidgets import QVBoxLayout

try:
    import rasterio
    import rasterio.control
    import rasterio.crs
    import rasterio.sample
    import rasterio.vrt
    import rasterio._features

    from rasterio.io import MemoryFile
    _rasterio_loaded = True
except Exception as e:
    print(f"Module 'rasterio' is not available: {e}")
    _rasterio_loaded = False

logger = logging.getLogger()


class WidgetInfo(PamhyrWidget):
    _pamhyr_ui = "MainWindowTabInfo"

    color_grey = "<font color='grey'>"
    color_end = "</font>"

    def __init__(self, study=None, parent=None):
        self._study = study

        super(WidgetInfo, self).__init__(
            parent=parent
        )

        self.parent = parent
        self.set_initial_values()
        self.setup_graph()

    @property
    def study(self):
        return self._study

    @study.setter
    def study(self, study):
        self._study = study

    def set_initial_values(self):
        self.set_label_text("label_study_name", "")
        self.set_text_edit_text("textBrowser_study", "")

        self.set_label_text("label_current_reach", "None")
        self.set_label_text("label_nodes", "-")
        self.set_label_text("label_edges", "-")

        self.set_label_text("label_cs", "-")
        self.set_label_text("label_points", "-")

        self.set_label_text("label_res", "-")
        self.set_label_text("label_bc", "-")
        self.set_label_text("label_lc", "-")
        self.set_label_text("label_hs", "-")

    def setup_graph(self):
        self.canvas = MplCanvas(width=5, height=4, dpi=100)
        self.canvas.setObjectName("canvas")
        self.plot_layout_xy = self.find(QVBoxLayout, "verticalLayout")
        self._toolbar_xy = PamhyrPlotToolbar(
            self.canvas, self,
            items=["home", "zoom", "save", "iso", "back/forward", "move"]
        )
        self.plot_layout_xy.addWidget(self._toolbar_xy)
        self.plot_layout_xy.addWidget(self.canvas)

        self.plot = PlotXY(
            canvas=self.canvas,
            data=None,
            trad=self.parent._trad,
            toolbar=self._toolbar_xy,
            parent=self
        )

    def update(self):
        if self._study is None:
            self.set_initial_values()
            return

        self.set_label_text("label_study_name", self._study.name)
        self.set_text_edit_text("textBrowser_study", self._study.description)

        self.set_network_values()
        self.set_geometry_values()

        self.plot = PlotXY(
            canvas=self.canvas,
            data=self._study.river.enable_edges(),
            geotiff=self._study.river.geotiff,
            trad=self.parent._trad,
            toolbar=self._toolbar_xy,
            parent=self
        )

        self.plot.update()

    def set_network_values(self):
        river = self._study.river

        n_nodes = river.enable_nodes_counts()
        n_d_nodes = river.nodes_counts() - n_nodes
        n_edges = river.enable_edges_counts()
        n_d_edges = river.edges_counts() - n_edges

        self.set_label_text(
            "label_nodes",
            f"{n_nodes} {self.color_grey}({n_d_nodes}){self.color_end}"
        )
        self.set_label_text(
            "label_edges",
            f"{n_edges} {self.color_grey}({n_d_edges}){self.color_end}"
        )

        current = river.current_reach()
        if current is not None:
            name = current.reach.name
        else:
            name = "None"
        self.set_label_text("label_current_reach", name)

        self.set_network_values_ext(river)

    def set_network_values_ext(self, river):
        self.set_network_values_ext_reservoir(river)
        self.set_network_values_ext_bc(river)
        self.set_network_values_ext_lc(river)

    def set_network_values_ext_reservoir(self, river):
        n_res = 0
        n_na_res = 0
        for res in river.reservoir.lst:
            if res.node is not None:
                n_res += 1
            else:
                n_na_res += 1

        self.set_label_text(
            "label_res",
            f"{n_res} {self.color_grey}({n_na_res}){self.color_end}"
        )

    def set_network_values_ext_bc(self, river):
        bc = river.boundary_condition
        n_bc = 0
        n_na_bc = 0

        for tab in bc._tabs_list:
            for c in bc.get_tab(tab):
                if c.node is not None:
                    n_bc += 1
                else:
                    n_na_bc += 1

        self.set_label_text(
            "label_bc",
            f"{n_bc} {self.color_grey}({n_na_bc}){self.color_end}"
        )

    def set_network_values_ext_lc(self, river):
        lc = river.lateral_contribution
        n_lc = 0
        n_na_lc = 0

        for tab in lc._tabs_list:
            for c in lc.get_tab(tab):
                if c.reach is not None:
                    n_lc += 1
                else:
                    n_na_lc += 1

        self.set_label_text(
            "label_lc",
            f"{n_lc} {self.color_grey}({n_na_lc}){self.color_end}"
        )

    def set_geometry_values(self):
        river = self._study.river

        n_cs = 0
        n_d_cs = 0
        n_points = 0
        n_d_points = 0

        for edge in river.edges():
            for profile in edge.reach.profiles:
                if edge.is_enable():
                    n_points += len(profile)
                    n_cs += 1
                else:
                    n_d_points += len(profile)
                    n_d_cs += 1

        self.set_label_text(
            "label_cs",
            f"{n_cs} {self.color_grey}({n_d_cs}){self.color_end}"
        )
        self.set_label_text(
            "label_points",
            f"{n_points} {self.color_grey}({n_d_points}){self.color_end}"
        )

        self.set_geometry_values_ext(river)

    def set_geometry_values_ext(self, river):
        self.set_geometry_values_ext_hs(river)

    def set_geometry_values_ext_hs(self, river):
        hs = river.hydraulic_structures
        n_hs = 0
        n_na_hs = 0

        for h in hs.lst:
            if h.input_reach is not None and h.input_rk is not None:
                n_hs += 1
            else:
                n_na_hs += 1

        self.set_label_text(
            "label_hs",
            f"{n_hs} {self.color_grey}({n_na_hs}){self.color_end}"
        )
