#!/usr/bin/env python3

"""
alarm_list.py
"""

__author__ = ["Benjamin Mummery", "Tiago Sarmento"]
__credits__ = ["Benjamin Mummery", "Dónal Murray", "Tim Powell", "Tiago Sarmento"]
__license__ = "GPL"
__version__ = "0.0.1"
__maintainer__ = "Tiago Sarmento"
__email__ = "tiago.sarmento@stfc.ac.uk"
__status__ = "Prototype"

from PySide2 import QtCore, QtWidgets


class AlarmTable(QtWidgets.QTableWidget):
    """
    Table containing all of the alarms since power up are contained. Easily sorted.

    TODO: unhardcode text sizes.
    """

    def __init__(self, NativeUI, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.header_keys = [
            "alarm_table_header_timestamp",
            "alarm_table_header_priority_level",
            "alarm_table_header_alarm_code",
            "alarm_table_header_duration",
        ]

        self.setSizePolicy(
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
        )
        self.setStyleSheet(
            "QWidget{"
            "   background-color:" + NativeUI.colors["table_background"].name() + ";"
            "   color:" + NativeUI.colors["table_foreground"].name() + ";"
            "}"
            "QHeaderView::section {"
            "   font-size: 20pt;"
            "}"
            "QTableWidget{"
            "   gridline-color:" + NativeUI.colors["table_foreground"].name() + ";"
            "   font-size: 20pt;"
            "}"
        )
        self.setFont(NativeUI.text_font)
        self.nrows = 0
        self.setColumnCount(4)
        self.setSortingEnabled(True)

        if self.nrows == 0:
            self.localise_text(NativeUI.text)

        self.payloadKeys = ["alarm_type", "alarm_code"]
        self.resizeColumnsToContents()

        self.alarm_cell_dict = {}
        self.timer = QtCore.QTimer()
        self.timer.setInterval(100)
        # self.timer.timeout.connect(self.update_duration)
        self.timer.start()

    def localise_text(self, text: dict) -> int:
        """
        Localise the text on the column headers
        """
        self.setHorizontalHeaderLabels([text[key] for key in self.header_keys])
        return 0

    def addAlarmRow(self, abstract_alarm):
        """Add a new row 1 cell at a time. Goes through alarm payload to fill information"""
        self.setSortingEnabled(False)
        self.setRowCount(self.nrows + 1)

        new_item = QtWidgets.QTableWidgetItem(str(abstract_alarm.startTime)[:-3])
        self.setItem(self.nrows, 0, new_item)

        new_item = QtWidgets.QTableWidgetItem(abstract_alarm.alarmPayload["alarm_type"])
        self.setItem(self.nrows, 1, new_item)

        new_item = QtWidgets.QTableWidgetItem(abstract_alarm.alarmPayload["alarm_code"])
        self.setItem(self.nrows, 2, new_item)

        new_item = QtWidgets.QTableWidgetItem(" ")
        self.alarm_cell_dict[self.nrows] = new_item
        self.setItem(self.nrows, 3, self.alarm_cell_dict[self.nrows])

        self.timer.timeout.connect(
            lambda i=self.alarm_cell_dict[
                self.nrows
            ], j=abstract_alarm: self.update_duration(i, j)
        )

        # if self.nrows == 1:
        self.resizeColumnsToContents()
        self.nrows = self.nrows + 1
        self.setSortingEnabled(True)

    def update_duration(self, cellItem, abstractAlarm):
        """Use abstractAlarm's duration attribute to update displayed duration."""
        cellItem.setText(str(abstractAlarm.duration))
