# -*- 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

        name = self.compute_name(study)

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

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

        self.ui.setWindowTitle(self._title)

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

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

        return (
            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
        )

        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=["sl"],
            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,
            toolbar=self.toolbar,
            display_current=False
        )
        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()
