# Window.py -- Pamhyr
# Copyright (C) 2023-2026  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.PamhyrWindow import PamhyrWindow
from View.Tools.PamhyrWidget import PamhyrWidget

from PyQt5.QtGui import (
    QKeySequence,
)

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

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

from View.Pollutants.Edit.Translate import EditPollutantTranslate
from View.Pollutants.Edit.Table import TableModel, ComboBoxDelegate

_translate = QCoreApplication.translate

logger = logging.getLogger()


class EditPolluantWindow(PamhyrWindow):
    _pamhyr_ui = "Pollutant"
    _pamhyr_name = "Edit Pollutant"

    def __init__(self, data=None, study=None, config=None, parent=None):
        self._data = data
        trad = EditPollutantTranslate()

        name = trad[self._pamhyr_name]
        if self._data is not None:
            name += (
                f" - {study.name} " +
                f" - {self._data.name}"
            )

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

        self._hash_data.append(data)

        self.setup_table()

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

        self._delegate_type = ComboBoxDelegate(
            trad=self._trad,
            parent=self
        )

        if self._study.is_editable():
            editable_headers = self._trad.get_dict("table_headers")
        else:
            editable_headers = []

        table = self.find(QTableView, "tableView")
        self._table = TableModel(
            table_view=table,
            table_headers=table_headers,
            editable_headers=editable_headers,
            delegates={"type": self._delegate_type},
            data=self._data,
            trad=self._trad,
            undo=self._undo_stack,
            opt_data=self._study.time_system
        )

        table.setModel(self._table)
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        table.setAlternatingRowColors(True)

    def index_selected_row(self):
        table = self.find(QTableView, "tableView")
        return table.selectionModel()\
                    .selectedRows()[0]\
                    .row()

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

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

        table = []
        # table.append(self._data.header)
        table.append(self._trad.get_dict("table_headers"))

        data = self._data.data
        for row in rows:
            table.append(list(data[row]))

        self.copyTableIntoClipboard(table)

    def _paste(self):
        header, data = self.parseClipboardTable()

        logger.debug(f"paste: header:{header}, data:{data}")

        if len(data) == 0:
            return

        row = 0
        rows = self.index_selected_rows()
        if len(rows) != 0:
            row = rows[0]

        self._table.paste(row, data)

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

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