import numpy as np
import pandas as pd
from PyQt5.QtGui import QFont

from PyQt5.QtWidgets import QMessageBox
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import QModelIndex, Qt, QAbstractTableModel, QVariant, QCoreApplication

from Model.Geometry.ProfileXYZ import ProfileXYZ

_translate = QCoreApplication.translate


class PandasModelEditable(QAbstractTableModel):
    def __init__(self, profile: ProfileXYZ, table_header=None):
        QAbstractTableModel.__init__(self)

        if table_header is None:
            self.header = ["X (m)", "Y (m)", "Z (m)", _translate("MainWindowProfile", "Nom"),
                           _translate("MainWindowProfile", "Abs en travers (m)")]
        else:
            self.header = table_header

        self.profile = profile

        data = pd.DataFrame({
            self.header[0]: profile.x(),
            self.header[1]: profile.y(),
            self.header[2]: profile.z(),
            self.header[3]: profile.name(),
            self.header[4]: profile.get_station()
        })
        self._data = data

    def rowCount(self, parent=QModelIndex()):
        return self._data.shape[0]

    def columnCount(self, parent=QModelIndex()):
        return self._data.shape[1]

    def data(self, index, role=Qt.DisplayRole):
        value = self._data.iloc[index.row()][index.column()]
        if index.isValid():
            if role == Qt.DisplayRole:
                if index.column() != 4:
                    if isinstance(value, float):
                        return "%.4f" % value
                else:
                    if isinstance(value, float):
                        return "%.3f" % value

                return str(self._data.iloc[index.row(), index.column()])

            if role == Qt.TextAlignmentRole:
                return Qt.AlignHCenter | Qt.AlignVCenter

            # if index.column() == 2:
            #     if role == Qt.ForegroundRole:
            #         if value == min(self._data.iloc[:, index.column()]):
            #             return QtGui.QColor("red")
            #         elif value == max(self._data.iloc[:, index.column()]):
            #             return QtGui.QColor("Blue")

                if role == Qt.ToolTipRole:
                    if value == min(self._data.iloc[:, index.column()]):
                        return _translate("MainWindowProfile", "La cote du fond", "Z minimale")
                    elif value == max(self._data.iloc[:, index.column()]):
                        return _translate("MainWindowProfile", "La cote maximale", "Z maximale")

            if index.column() == 3:
                if value.strip().upper() in ["RG", "RD"]:
                    if role == Qt.FontRole:
                        font = QFont()
                        font.setBold(True)
                        return font

                    if role == Qt.ForegroundRole:
                        return QtGui.QColor("darkRed")

                    if role == Qt.ToolTipRole:
                        if value.strip().upper() == "RG":
                            return _translate("MainWindowProfile", "Rive gauche")
                        else:
                            return _translate("MainWindowProfile", "Rive droite")

            if index.column() == 4:
                if role == Qt.FontRole:
                    font = QFont()
                    font.setBold(True)
                    return font

                # if role == Qt.BackgroundRole:
                #     return QtGui.QColor("#ededee")

        return QVariant()

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.header[section]

        if role == Qt.ToolTipRole and section == 4:
            return _translate(
                "MainWindowProfile",
                "Abscisse en travers calculée en projétant les points"
                " \nsur le plan défini par les deux points nommés extrêmes "
            )

        if orientation == Qt.Vertical and role == Qt.DisplayRole:
            return self._data.index[section] + 1

        return None

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.EditRole:
            try:
                if index.column() == 3:
                    self._data.iat[index.row(), index.column()] = str(value)
                elif index.column() == 0:
                    self._data.iat[index.row(), index.column()] = float(value)
                elif index.column() == 1:
                    self._data.iat[index.row(), index.column()] = float(value)
                elif index.column() == 2:
                    self._data.iat[index.row(), index.column()] = float(value)

                self._data.iloc[:, 4] = projection_pointXYZ.update_station(
                    self.header,
                    self._data.values.tolist()
                )
                self.dataChanged.emit(index, index)
            except:
                print('TODO')
                self.QMessageBoxCritical(value)

            return True

        self.dataChanged.emit(index, index)
        self.layoutChanged.emit()

        return False

    @staticmethod
    def QMessageBoxCritical(value):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setText("{} : Valeur saisie incorrecte ".format(value))
        msg.setInformativeText("Seules les valeurs numériques sont autorisées.")
        msg.setWindowTitle("Warning ")
        msg.setStyleSheet("QLabel{min-width:150 px; font-size: 13px;} QPushButton{ width:20px; font-size: 12px};"
                          "background-color: Ligthgray ; color : gray;font-size: 8pt; color: #888a80;")
        msg.exec_()

    def index(self, row, column, parent=QModelIndex()):
        if not self.hasIndex(row, column, parent):
            return QModelIndex()
        return self.createIndex(row, column, QModelIndex())

    def flags(self, index):
        return Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled

    # @QtCore.pyqtSlot()
    def insertRows(self, row, count, parent=QModelIndex()):
        self.beginInsertRows(parent, row, row + count - 1)
        indexes = [str(self.rowCount() + i) for i in range(count)]
        left = self._data[0:row]
        mid = pd.DataFrame(index=indexes, columns=self._data.columns)
        right = self._data[row + count - 1:self.rowCount()]

        self._data = pd.concat([left, mid, right])

        for i in [3]:
            self._data.iloc[:, i].replace(np.nan, '', inplace=True)

        self._data.reset_index(drop=True, inplace=True)

        try:
            self._data.iloc[:, 4] = projection_pointXYZ.update_station(
                self.header,
                self._data.values.tolist()
            )
        except:
            print("TODO")

        self.endInsertRows()
        self.layoutChanged.emit()

    # @QtCore.pyqtSlot()
    def removeRows(self, row, count, parent=QModelIndex()):
        self.beginRemoveRows(parent, row, row + count + 1)
        self._data.drop(self._data.index[row], inplace=True)
        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )
        self.endRemoveRows()
        self.layoutChanged.emit()

    def remove_rows1(self, row, count, parent=QModelIndex()):
        self.beginRemoveRows(parent, row, row + count - 1)
        left = self._data.iloc[0:row]
        right = self._data.iloc[row + count:self.rowCount()]

        self._data = pd.concat([left, right], axis=0, ignore_index=True)
        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )
        self.endRemoveRows()
        self.layoutChanged.emit()

    def remove_rows(self, list_row_selected, parent=QModelIndex()):
        self.beginRemoveRows(parent, list_row_selected[0], list_row_selected[-1])

        try:
            self._data.drop(self._data.index[list_row_selected], inplace=True)
            self._data.reset_index(drop=True, inplace=True)
        except:
            print('TODO')
        try:
            self._data.iloc[:, 4] = projection_pointXYZ.update_station(
                self.header,
                self._data.values.tolist()
            )
        except:
            print("TODO")

        self.endRemoveRows()
        self.layoutChanged.emit()

    def sort(self, column, order=Qt.AscendingOrder):
        self.layoutAboutToBeChanged.emit()
        colname = self._data.columns.tolist()[column]
        self._data.sort_values(colname, ascending=order == Qt.AscendingOrder, inplace=True)
        self._data.reset_index(inplace=True, drop=True)

        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )
        self.layoutChanged.emit()

    def moveRowDown(self, row_to_move, parent=QModelIndex()):
        target = row_to_move + 2
        self.beginMoveRows(parent, row_to_move, row_to_move, parent, target)
        block_before_row = self._data.iloc[0:row_to_move]
        selected_row = self._data.iloc[row_to_move:row_to_move + 1]
        after_selcted_row = self._data.iloc[row_to_move + 1:row_to_move + 2]
        block_after_row = self._data.iloc[row_to_move + 2:self.rowCount()]

        self._data = pd.concat([block_before_row, after_selcted_row, selected_row, block_after_row], axis=0)
        self._data.reset_index(inplace=True, drop=True)

        self.endMoveRows()
        self.layoutChanged.emit()

    def moveRowUp(self, row_to_move, parent=QModelIndex()):
        target = row_to_move + 1
        self.beginMoveRows(parent, row_to_move - 1, row_to_move - 1, parent, target)
        block_before_row = self._data.iloc[0:row_to_move - 1]
        before_selected_row = self._data.iloc[row_to_move - 1:row_to_move]
        selected_row = self._data.iloc[row_to_move:row_to_move + 1]
        block_after_row = self._data.iloc[row_to_move + 1:self.rowCount()]

        self._data = pd.concat([block_before_row, selected_row, before_selected_row, block_after_row], axis=0)
        self._data.reset_index(inplace=True, drop=True)

        self.endMoveRows()
        self.layoutChanged.emit()

    def copyTable(self, start_selection, end_selection):
        end_selection = self.rowCount()

        self._data.loc[start_selection:end_selection]\
                  .to_clipboard(header=None, index=False, excel=True, sep='\t')

    def insert_df_to_idx(self, idx, df, df_insert):
        """
        Args:
            idx: is the index position in df where you want to insert new dataframe (df_insert)
            df: dataframe
            df_insert: dataframe to insert
        Returns:
            The dataframe df with df_insert inserted at index idx.
        """
        return df.iloc[:idx, ].append(df_insert).append(df.iloc[idx:, ]).reset_index(drop=True)

    def pasteTable(self, insertion_index):
        self.layoutAboutToBeChanged.emit()
        df = pd.read_clipboard(header=None, skip_blank_lines=True,
                               sep="\t", names=self.header)
        self._data = self.insert_df_to_idx(insertion_index, self._data, df)

        for i in [3]:
            self._data.iloc[:, i].replace(np.nan, '', inplace=True)

        self.layoutChanged.emit()
        self._data.iloc[:, 4] = projection_pointXYZ.update_station(
            self.header,
            self._data.values.tolist()
        )

    @property
    def model_data(self):
        return self._data

    @model_data.setter
    def model_data(self, new_data):
        self._data = new_data
        self.layoutChanged.emit()

    @property
    def x(self):
        return self._data.iloc[:, 0].tolist()

    @property
    def y(self):
        return self._data.iloc[:, 1].tolist()

    @property
    def z(self):
        return self._data.iloc[:, 2].tolist()

    @property
    def name(self):
        return self._data.iloc[:, 3].tolist()

    def get_data(self):
        return self._data

    @property
    def station(self):
        return self._data.iloc[:, 4].tolist()

    def remove_duplicates_names(self):
        counter_list = []
        list_deleted_names = []
        ind_ind = []

        for ind, name_point in enumerate(self.name):
            if name_point not in counter_list:
                counter_list.append(name_point)
            elif len(name_point.strip()) > 0 and name_point in counter_list:
                ind_ind.append(ind)

                if name_point not in list_deleted_names:
                    list_deleted_names.append(name_point)

        for ind in ind_ind:
            self._data.iat[ind, 3] = ""

    def data_contains_nan(self) -> bool:
        """
        Returns:
            Returns True if the QTableView() contains np.nan
        """
        return self._data.isnull().values.any()

    def delete_empty_rows(self):
        self.layoutAboutToBeChanged.emit()

        self._data.dropna(inplace=True)
        self._data.reset_index(drop=True, inplace=True)

        self.layoutChanged.emit()

    def valide_all_changes(self):
        self.profile.x = self._data.iloc[:, 0]
        self.profile.y = self._data.iloc[:, 1]
        self.profile.z = self._data.iloc[:, 2]
        self.profile.ld = self._data.iloc[:, 3]


class Delegate(QtWidgets.QStyledItemDelegate):
    def __init__(self, parent=None, setModelDataEvent=None):
        super(Delegate, self).__init__(parent)
        self.setModelDataEvent = setModelDataEvent

    def createEditor(self, parent, option, index):
        """
        Args:
            parent:
            option:
            index:
        Returns:
            Le widget (éditeur) pour éditer l'item se trouvant à l'index index.
        """
        index.model().data(index, Qt.DisplayRole)
        return QtWidgets.QLineEdit(parent)

    def setEditorData(self, editor, index):
        """
        Args:
            editor: l'éditeur
            index: l'index
        Returns: permet de transmettre à l'éditeur editor les données à afficher à partir du modèle se trouvant
                à l'index index.
        """
        value = index.model().data(index, Qt.DisplayRole)
        editor.setText(str(value))

    def setModelData(self, editor, model, index):
        """
        Args:
            editor: l'éditeur
            model: le modèle
            index: l'index
        Returns: permet de récupérer les données de l'éditeur et de les stocker à l'intérieur du modèle, à l'index
                identifié par le paramètre index
        """
        model.setData(index, editor.text())

        if not self.setModelDataEvent is None:
            self.setModelDataEvent()

    def updateEditorGeometry(self, editor, option, index):
        """
        Args:
            editor: l'éditeur
            option:
            index: l'index
        Returns: Permet de redimensionner l'éditeur à la bonne taille lorsque la taille de la vue change
        """
        editor.setGeometry(option.rect)