# Copyright 2021 Vincent Texier <vit@free.fr>
#
# This software 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 software 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 <http://www.gnu.org/licenses/>.

from typing import List

from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt, QVariant

from tikka.domains.application import Application
from tikka.domains.entities.technical_committee import TechnicalCommitteeMember
from tikka.interfaces.adapters.repository.technical_committee_members import (
    TechnicalCommitteeMembersRepositoryInterface,
)


class TechnicalCommitteeMembersTableModel(QAbstractTableModel):
    """
    TechnicalCommitteeMembersTableModel class that drives the population of tabular display
    """

    def __init__(self, application: Application):
        super().__init__()

        self.application = application

        self.members: List[TechnicalCommitteeMember] = []
        self.init_data()

    def init_data(self):
        """
        Fill data from repository

        :return:
        """
        self.beginResetModel()
        self.members = self.application.technical_committee.list_members(
            sort_column=TechnicalCommitteeMembersRepositoryInterface.COLUMN_IDENTITY_NAME,
            sort_order=TechnicalCommitteeMembersRepositoryInterface.SORT_ORDER_ASCENDING,
        )
        self.endResetModel()

    def rowCount(self, _: QModelIndex = QModelIndex()) -> int:
        """
        Return row count

        :param _: QModelIndex instance
        :return:
        """
        return len(self.members)

    def columnCount(self, _: QModelIndex = QModelIndex()) -> int:
        """
        Return column count (length of headers list)

        :param _: QModelIndex instance
        :return:
        """
        return 2

    def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> QVariant:
        """
        Return data of cell for column index.column

        :param index: QModelIndex instance
        :param role: Item data role
        :return:
        """
        col = index.column()
        row = index.row()
        member = self.members[row]
        data = QVariant()
        if role == Qt.DisplayRole:
            if col == 0:
                data = QVariant(member.address)
            if col == 1:
                if member.identity_index is not None:
                    data = QVariant(f"{member.identity_name}#{member.identity_index}")
        return data
