# 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.Profile.UndoCommand import *
from View.SedimentLayers.Reach.Profile.Table import *
from View.SedimentLayers.Reach.Profile.Plot import Plot

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

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

_translate = QCoreApplication.translate

logger = logging.getLogger()


class ProfileSedimentLayersWindow(PamhyrWindow):
    _pamhyr_ui = "ProfileSedimentLayers"
    _pamhyr_name = "Profile sediment layers"

    def __init__(self, study=None, config=None, profile=None, parent=None):
        self._sediment_layers = study.river.sediment_layers
        self._profile = profile
        self._reach = profile.reach

        trad = SedimentProfileTranslate()
        name = self.compute_name(study, trad)

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

        self.setup_table()
        self.setup_graph()
        self.setup_connections()

    def compute_name(self, study, trad):
        rname = self._reach.name
        if rname == "":
            rname = _translate("SedimentLayers", "(no name)")

        pname = self._profile.name
        if pname == "":
            pname = _translate(
                "SedimentLayers",
                "(no name - @rk)").replace(
                    "@rk", str(self._profile.rk)
                )

        return (
            trad[self._pamhyr_name] + " - "
            + study.name + " - "
            + rname + " - " + pname
        )

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

        self._delegate_sl = ComboBoxDelegate(
            study=self._study,
            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._profile,
            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_graph(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")
        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._profile,
            trad=self._trad,
            toolbar=self.toolbar,
        )
        self.plot.draw()

    def setup_connections(self):
        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()

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