# Window.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 trace, timer

from View.Tools.PamhyrWindow import PamhyrWindow

from PyQt5.QtGui import (
    QKeySequence,
)

from PyQt5.QtCore import (
    Qt, QVariant, QAbstractTableModel,
    QCoreApplication, QModelIndex, pyqtSlot,
    QRect,
)

from PyQt5.QtWidgets import (
    QDialogButtonBox, QPushButton, QLineEdit,
    QFileDialog, QTableView, QAbstractItemView,
    QUndoStack, QShortcut, QAction, QItemDelegate,
    QComboBox, QVBoxLayout, QHeaderView, QTabWidget,
)

from View.SedimentLayers.Reach.UndoCommand import *
from View.SedimentLayers.Reach.Table import *
from View.SedimentLayers.Reach.Plot import Plot
from View.SedimentLayers.Reach.SLDialog import SLDialog

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

from View.SedimentLayers.Reach.translate import SedimentReachTranslate
from View.SedimentLayers.Window import SedimentLayersWindow
from View.SedimentLayers.Reach.Profile.Window import (
    ProfileSedimentLayersWindow
)

_translate = QCoreApplication.translate

logger = logging.getLogger()


class ReachSedimentLayersWindow(PamhyrWindow):
    _pamhyr_ui = "ReachSedimentLayers"
    _pamhyr_name = "Reach sediment layers"

    def __init__(self, study=None, config=None, reach=None, parent=None):
        self._sediment_layers = study.river.sediment_layers
        if reach is None:
            self._reach = study.river.current_reach().reach
        else:
            self._reach = reach

        trad = SedimentReachTranslate()
        name = (
            trad[self._pamhyr_name] + " - " +
            study.name + " - " +
            self._reach.name
        )

        super(ReachSedimentLayersWindow, self).__init__(
            title=name,
            study=study,
            config=config,
            trad=trad,
            parent=parent
        )

        # Add reach to hash computation data
        self._hash_data.append(self._reach)

        self.setup_table()
        self.setup_plot()
        self.setup_connections()

    def setup_table(self):
        table_headers = self._trad.get_dict("table_headers")

        self._delegate_sl = ComboBoxDelegate(
            study=self._study,
            trad=self._trad,
            parent=self
        )

        if self._study.is_editable():
            editable_headers = ["sl"]
        else:
            editable_headers = []

        table = self.find(QTableView, f"tableView")
        self._table = TableModel(
            table_view=table,
            data=self._reach,
            opt_data=self._study,
            table_headers=table_headers,
            editable_headers=editable_headers,
            delegates={"sl": self._delegate_sl},
            trad=self._trad,
            undo=self._undo_stack,
        )
        table.setModel(self._table)
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        table.setAlternatingRowColors(True)

    def setup_plot(self):
        self.canvas = MplCanvas(width=5, height=4, dpi=100)
        self.canvas.setObjectName("canvas")
        self.toolbar = PamhyrPlotToolbar(
            self.canvas, self
        )
        self.plot_layout = self.find(QVBoxLayout, "verticalLayout_2")
        self.plot_layout.addWidget(self.toolbar)
        self.plot_layout.addWidget(self.canvas)

        self._update_plot()

    def _update_plot(self):
        self.plot = Plot(
            canvas=self.canvas,
            data=self._reach,
            toolbar=self.toolbar,
            trad=self._trad,
        )
        self.plot.draw()

    def setup_connections(self):
        self.find(QAction, "action_edit").triggered.connect(self.edit_profile)

        self.find(QPushButton, "pushButton_edit")\
            .clicked\
            .connect(self.edit_sl)

        if self._study.is_editable():
            self.find(QPushButton, "pushButton_apply")\
                .clicked.connect(self.apply_sl_each_profile)

        self._table.layoutChanged\
                   .connect(self._update_plot)
        self._table.dataChanged\
                   .connect(self._update_plot)

    def index_selected_rows(self):
        table = self.find(QTableView, f"tableView")
        return list(
            # Delete duplicate
            set(
                map(
                    lambda i: i.row(),
                    table.selectedIndexes()
                )
            )
        )

    def _copy(self):
        logger.info("TODO: copy")

    def _paste(self):
        logger.info("TODO: paste")

    def _undo(self):
        self._table.undo()
        self._update_plot()

    def _redo(self):
        self._table.redo()
        self._update_plot()

    def apply_sl_each_profile(self):
        slw = SLDialog(
            study=self._study,
            trad=self._trad,
            parent=self
        )
        if slw.exec():
            sl = slw.sl
            self._table.apply_sl_each_profile(sl)

        self._update_plot()

    def edit_profile(self):
        rows = self.index_selected_rows()

        for row in rows:
            slw = ProfileSedimentLayersWindow(
                study=self._study,
                profile=self._reach.profile(row),
                parent=self
            )
            slw.show()

    def edit_sl(self):
        slw = SedimentLayersWindow(
            study=self._study,
            parent=self
        )
        slw.show()
