#!/usr/bin/env python3

"""
alarm_control_widget.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 QtWidgets, QtGui, QtCore
import os
import logging


class AlarmControlWidget(QtWidgets.QWidget):
    def __init__(self, NativeUI, test=False, *args, **kwargs):
        super().__init__(*args, **kwargs)
        """Button controlling alarm volume and mute. There are 3 volume options and a mute button """
        self.NativeUI = NativeUI
        self.volState = 2
        nVolSteps = 3
        self.volButtonsList = []
        self.volTruth = [0] * nVolSteps
        hlayout = QtWidgets.QHBoxLayout()

        for i in range(0, nVolSteps):
            self.volButtonsList.append(QtWidgets.QPushButton())
            self.volButtonsList[-1].setStyleSheet(
                "QPushButton{"
                "    background-color:"
                + NativeUI.colors["page_foreground"].name()
                + "; border:none;"
                "}"
                "QPushButton[bgColour='1']{"
                "    background-color:"
                + NativeUI.colors["button_background_highlight"].name()
                + ";border: none;"
                "}"
                "QPushButton[bgColour='0']{"
                "    background-color:"
                + NativeUI.colors["page_foreground"].name()
                + "; border:none;"
                "}"
            )
            self.volButtonsList[-1].pressed.connect(lambda k=i: self.buttonPushed(k))
            hlayout.addWidget(self.volButtonsList[-1])
        self.buttonPushed(self.volState)

        self.iconStack = QtWidgets.QStackedWidget()
        self.onSpeakers = QtWidgets.QPushButton()
        self.onSpeakers.pressed.connect(self.mute_pressed)
        self.onSpeakers.setStyleSheet(
            "background-color: "
            + NativeUI.colors["button_background_enabled"].name()
            + "; border:none;"
            + "color:" + NativeUI.colors["page_foreground"].name() + ";"
        )
        self.iconStack.addWidget(self.onSpeakers)
        self.offSpeakers = QtWidgets.QPushButton()
        self.offSpeakers.pressed.connect(self.unmute_pressed)
        self.offSpeakers.setStyleSheet(
            "background-color: "
            + NativeUI.colors["button_background_enabled"].name()
            + "; border:none;"
            + "color:" + NativeUI.colors["page_foreground"].name() + ";"
        )
        self.iconStack.addWidget(self.offSpeakers)
        hlayout.addWidget(self.iconStack)
        if test:
            self.testSpeakers = QtWidgets.QPushButton("Test Alarm")
            self.setMaximumHeight(100)
            self.iconStack.addWidget(self.testSpeakers)
            self.iconStack.setCurrentWidget(self.testSpeakers)
            self.testSpeakers.pressed.connect(self.test_speakers)

        self.__icon_path = os.path.join(NativeUI.iconpath, "bell-solid.png")
        pixmap = QtGui.QPixmap(self.__icon_path)
        mask = pixmap.mask()
        pixmap.fill(NativeUI.colors["plot_pressure_flow"])
        pixmap.setMask(mask)
        self.onSpeakers.setIcon(QtGui.QIcon(pixmap))

        # self.__icon_path = os.path.join(NativeUI.iconpath, "bell-regular.png")
        # pixmap = QtGui.QPixmap(self.__icon_path)
        # mask = pixmap.mask()
        # pixmap.fill(NativeUI.colors["plot_flow"])
        # pixmap.setMask(mask)
        # self.offSpeakers.setIcon(QtGui.QIcon(pixmap))

        # self.timeLabel = QtWidgets.QLabel("")
        self.offSpeakers.setFont(NativeUI.value_font)
        # self.timeLabel.setStyleSheet(
        #     "color:" + NativeUI.colors["page_foreground"].name() + ";"
        # )
        # hlayout.addWidget(self.timeLabel)
        self.setLayout(hlayout)

        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000)  # just faster than 60Hz
        self.timer.timeout.connect(self.mute_timer)

        self.volumeCodes = {0:'QUIET', 1:'LOUD', 2:'LOUDEST'}
        # self.timer.start()

    def mute_timer(self):
        self.remaining_mute_time += -1
        self.offSpeakers.setText(str(self.remaining_mute_time))
        if self.remaining_mute_time == 0:
            self.unmute_pressed()

    def mute_pressed(self):
        """Mute button pressed. Switched to unmute button and sends Mute command"""
        self.buttonPushed(-1)
        self.iconStack.setCurrentWidget(self.offSpeakers)
        #self.NativeUI.q_send_cmd("MUTE_ALARM", "TRUE")
        self.remaining_mute_time = 120
        self.timer.start()

    def unmute_pressed(self):
        self.timer.stop()
        self.remaining_mute_time = 120
        self.offSpeakers.setText("120")
        self.buttonPushed(self.volState)
        self.iconStack.setCurrentWidget(self.onSpeakers)
        #self.NativeUI.q_send_cmd("MUTE_ALARM", "FALSE")

    def test_speakers(self):
        logging.debug("testin!")
        logging.debug(self.volState)
        #self.NativeUI.q_send_cmd("TEST_AUDIO_ALARM")

    def buttonPushed(self, index):
        if index != -1:
            self.volState = index
        for i in range(0, index + 1):
            # self.volTruth[i] = int(not self.volTruth[i]
            self.volButtonsList[i].setProperty("bgColour", str(1))
            self.volButtonsList[i].style().polish(self.volButtonsList[i])

        for i in range(index + 1, len(self.volButtonsList)):
            self.volButtonsList[i].setProperty("bgColour", str(0))
            self.volButtonsList[i].style().polish(self.volButtonsList[i])

        # self.volButtonsList[i].style().polish(self.volButtonsList[index])
        self.style().polish(self)
        if index == -1:
            for i in range(0, len(self.volButtonsList)):
                self.volButtonsList[i].setProperty("bgColour", str(0))
                self.volButtonsList[i].style().polish(self.volButtonsList[i])
        elif index >= 0:
            try:
                self.NativeUI.q_send_cmd("SET_VOLUME", self.volumeCodes[index])
            except:
                logging.debug('didnt work')

    def set_size(self, x: int, y: int, spacing=10) -> int:
        if x < 2.2*y:
            x = 2.2*y
        self.setFixedSize(x, y)
        self.offSpeakers.setFixedSize(1.1*y,y)
        self.onSpeakers.setFixedSize(1.1*y,y)
        return 0

    def localise_text(self, text: dict) -> int:
        """
        Change the language of text elements.
        """
        pass


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    widg = AlarmControlButton("a")
    widg.show()
    sys.exit(app.exec_())
