#!/usr/bin/env python3

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

os.environ["QT_IM_MODULE"] = "qtvirtualkeyboard"

from widget_library.ok_cancel_buttons_widget import OkButtonWidget, CancelButtonWidget, styledTextButton
from widget_library.numpad_widget import NumberpadWidget, AlphapadWidget


class AbstractTypeValPopup(QtWidgets.QDialog):
    """Popup takes user input to put in spin box. """

    okPressed = QtCore.Signal(str)
    cancelPressed = QtCore.Signal()
    correctPassword = QtCore.Signal()

    def __init__(self, NativeUI, characterType, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.NativeUI = NativeUI
        # self.label_text = label_text
        # self.min, self.max, self.initVal, self.step, self.decPlaces = min, max, initVal, step, decPlaces
        grid = QtWidgets.QGridLayout()
        grid.setSpacing(1)

        # self.label_text, self.min, self.max, self.initVal, self.step, self.decPlaces = 'Enter Password', 0, 10000, 0, 0, 0

        self.setStyleSheet("background-color:black")
        self.characterType = characterType
        self.label = QtWidgets.QLabel()  # self.label_text)
        self.label.setFont(NativeUI.value_font)
        self.label.setStyleSheet("color: " + NativeUI.colors["page_foreground"].name())
        self.label.setAlignment(QtCore.Qt.AlignCenter)

        self.lineEdit = QtWidgets.QLineEdit()
        self.lineEdit.setText("4")
        self.lineEdit.setStyleSheet(
            "QLineEdit{"
            "   background-color: white;"
            # "   border-radius: 4px;"
            "}"
            "QLineEdit[colour = '0']{"
            "   color: green;"
            "}"
            "QLineEdit[colour = '1']{"
            "   color: rgb(144, 231, 211);"
            "}"
            "QLineEdit[colour = '2']{"
            "   color: red;"
            "}"
        )
        self.lineEdit.setFont(NativeUI.value_font)
        self.lineEdit.setProperty("colour", "1")
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.lineEdit.saveVal = ""  # self.lineEdit.text()
        self.lineEdit.setFixedHeight(self.NativeUI.screen_height / 12)
        self.lineEdit.setFixedWidth(self.NativeUI.screen_width / 7)
        self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)

        hlayout = QtWidgets.QHBoxLayout()
        if characterType == "numeric":
            self.lineEdit.setValidator(
                QtGui.QDoubleValidator(0.0, 100.0, 5)
            )  # ensures only doubles can be typed, do
            # self.lineEdit.textEdited.connect(self.setTextColour(1))
            self.numberpad = NumberpadWidget(NativeUI)
            self.numberpad.numberPressed.connect(self.handle_numberpress)

            self.increaseButton = styledTextButton(NativeUI, text="+")
            self.increaseButton.clicked.connect(self.increase_button_clicked)
            self.increaseButton.setEnabled(True)
            self.increaseButton.setFixedWidth(self.NativeUI.screen_width / 7)
            self.increaseButton.setFixedHeight(self.NativeUI.screen_height / 12)

            self.decreaseButton = styledTextButton(NativeUI, text="-")
            self.decreaseButton.clicked.connect(self.decrease_button_clicked)
            self.decreaseButton.setEnabled(True)
            self.decreaseButton.setFixedWidth(self.NativeUI.screen_width / 8)
            self.decreaseButton.setFixedHeight(self.NativeUI.screen_height / 12)
            hlayout.addStretch(0)
            hlayout.addWidget(self.decreaseButton)
            hlayout.addWidget(self.lineEdit)
            hlayout.addWidget(self.increaseButton)
            hlayout.addStretch(0)
            # hlayout.addWidget(QtWidgets.QSpacerItem())
        if characterType == "alpha":
            self.lineEdit.setFixedWidth(self.NativeUI.screen_width / 2)
            self.numberpad = AlphapadWidget(NativeUI)
            self.numberpad.numberPressed.connect(self.handle_alphapress)
            hlayout.addWidget(self.lineEdit)

        self.hlayout2 = QtWidgets.QHBoxLayout()

        self.okButton = OkButtonWidget(NativeUI)
        # self.okButton.setEnabled(True)
        self.hlayout2.addWidget(self.okButton)

        self.cancelButton = CancelButtonWidget(NativeUI)
        self.cancelButton.setColour(str(int(True)))

        self.hlayout2.addWidget(self.cancelButton)

        vlayout = QtWidgets.QVBoxLayout()
        vlayout.addWidget(self.label)
        vlayout.addLayout(hlayout)
        vlayout.addWidget(self.numberpad)
        vlayout.addLayout((self.hlayout2))

        self.setLayout(vlayout)
        self.setWindowFlags(
            QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint
        )  # no window title
        self.password = "A"

    def submit_password(self):
        val = self.lineEdit.text()
        if val == self.password:
            self.correctPassword.emit()
        self.lineEdit.setText("")  # reset text whether or not password was successful

    def handle_ok_press(self):
        val = self.lineEdit.text()
        if self.characterType == "numeric":
            val = float(val)
        self.NativeUI.display_stack.setCurrentWidget(self.return_stack_widget)
        if val != self.currentWidg.value():
            self.currentWidg.setValue(val)
            self.currentWidg.manualChanged.emit()

    def handle_cancel_press(self):
        if isinstance(self.initVal, float):
            self.currentWidg.setValue(self.initVal)
        if isinstance(self.initVal, str):
            self.currentWidg.setText(self.initVal)

        self.NativeUI.display_stack.setCurrentWidget(self.return_stack_widget)

    def populatePopup(self, currentWidg, return_widget):
        self.currentWidg = currentWidg
        self.return_stack_widget = return_widget
        if self.characterType == "numeric":
            self.okButton.setColour(str(int(False)))
            self.label_text, self.min, self.max, self.initVal, self.step, self.decPlaces = (
                currentWidg.label_text,
                currentWidg.min,
                currentWidg.max,
                currentWidg.value(),
                currentWidg.step,
                currentWidg.decPlaces,
            )
            # if currentWidg.min < 0:
            self.lineEdit.setText(str(self.initVal))  #'-' + str())
            # else:
            #   self.lineEdit.setText('')  # str(currentWidg.value()))
        else:
            self.label_text = currentWidg.label_text
            self.initVal = currentWidg.value()
            self.lineEdit.setText(self.initVal)
            # self.okButton.setColour(str(int(True)))
        self.label.setText(self.label_text)

    def handle_numberpress(self, symbol):
        """Handle number pad button press. Put button value in line edit text, and handle inputs
        outside accepted range or number of decimal places. Handle backspace"""
        logging.debug(symbol)
        oldText = self.lineEdit.text()
        newText = oldText
        if symbol.isnumeric() or (symbol == "."):
            newText = oldText + symbol
            if float(newText) > self.max:
                newText = str(self.max)
            elif float(newText) < self.min:
                a = 1
                # newText = str(self.min)
            elif "." in newText:
                if len(newText.split(".")[1]) > self.decPlaces:
                    newText = oldText
            self.lineEdit.setText(newText)
        elif symbol == "<":
            if oldText[-1] == "-":
                return 0
            else:
                newText = oldText[0:-1]
                self.lineEdit.setText(newText)
        elif symbol == "CLEAR":
            if self.characterType == "numeric" and self.min < 0:
                self.lineEdit.setText("-")
            else:
                self.lineEdit.setText("")

        else:
            logging.debug("handle_numberpress - unrecognised symbol: %s", symbol)

        self.check_in_range(float(newText))
        return 0

    def handle_alphapress(self, symbol):
        """Handle alphapad button press. Put button value in line edit text, and handle inputs
        outside accepted range or number of decimal places. Handle backspace"""

        oldText = self.lineEdit.text()
        if symbol == "CLEAR":
            self.lineEdit.setText("")
        elif symbol == "SPACE":
            self.lineEdit.setText(oldText + " ")
        elif symbol.isalpha() or symbol.isnumeric():
            newText = oldText + symbol
            self.lineEdit.setText(newText)
        elif symbol == "<":
            self.lineEdit.setText(oldText[0:-1])

        self.okButton.setColour(str(int(True)))

    def check_in_range(self, value):
        if self.min <= value <= self.max:
            inrange = True
        else:
            inrange = False
        self.okButton.setColour(str(int(inrange)))

    def increase_button_clicked(self):
        """Handle increase step button click"""
        currentVal = self.get_value()
        newVal = round(float(currentVal) + self.step, self.decPlaces)
        if newVal >= self.max:
            newVal = self.max

        self.check_in_range(newVal)
        self.lineEdit.setText(str(newVal))
        return 0

    def decrease_button_clicked(self):
        """Handle decrease step button click"""
        currentVal = self.get_value()
        newVal = round(float(currentVal) - self.step, self.decPlaces)
        if newVal <= self.min:
            newVal = self.min
        self.check_in_range(newVal)
        self.lineEdit.setText(str(newVal))
        return 0

    def get_value(self):
        return self.lineEdit.text()

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


#
# class TypeValuePopup():
#     """Popup takes user input to put in spin box. """
#     okPressed = QtCore.Signal(str)
#     cancelPressed = QtCore.Signal()
#
#     def __init__(self, NativeUI, keyboard, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#
#         #self.label_text = label_text
#         #self.min, self.max, self.initVal, self.step, self.decPlaces = min, max, initVal, step, decPlaces
#         grid = QtWidgets.QGridLayout()
#         grid.setSpacing(1)
#
#         self.setStyleSheet("border-radius:4px; background-color:black")
#
#         self.label = QtWidgets.QLabel()#self.label_text)
#         self.label.setFont(NativeUI.text_font)
#         self.label.setStyleSheet('color: ' + NativeUI.colors["page_foreground"].name())
#
#         self.lineEdit = QtWidgets.QLineEdit()
#         self.lineEdit.setText("4")
#         self.lineEdit.setStyleSheet(
#             "QLineEdit{"
#             "   background-color: white;"
#             "   border-radius: 4px;"
#             "}"
#             "QLineEdit[colour = '0']{"
#             "   color: green;"
#             "}"
#             "QLineEdit[colour = '1']{"
#             "   color: rgb(144, 231, 211);"
#             "}"
#             "QLineEdit[colour = '2']{"
#             "   color: red;"
#             "}"
#         )
#         self.lineEdit.setFont(NativeUI.text_font)
#         self.lineEdit.setProperty("colour", "1")
#         self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
#         self.lineEdit.saveVal = ''#self.lineEdit.text()
#         self.lineEdit.setValidator(
#             QtGui.QDoubleValidator(0.0, 100.0, 5)
#         )  # ensures only doubles can be typed, do
#         # self.lineEdit.textEdited.connect(self.setTextColour(1))
#
#         self.numberpad = keyboard#NumberpadWidget(NativeUI)
#         self.numberpad.numberPressed.connect(self.handle_numberpress)
#
#         self.increaseButton = OkButtonWidget(NativeUI)
#         self.increaseButton.clicked.connect(self.increase_button_clicked)
#         self.increaseButton.setEnabled(True)
#
#         self.decreaseButton = CancelButtonWidget(NativeUI)
#         self.decreaseButton.clicked.connect(self.decrease_button_clicked)
#         self.decreaseButton.setEnabled(True)
#
#         #grid.addWidget(self.lineEdit, 0, 0, 1, 2)
#         hlayout = QtWidgets.QHBoxLayout()
#         hlayout.addWidget(self.decreaseButton)
#         hlayout.addWidget(self.lineEdit)
#         hlayout.addWidget(self.increaseButton)
#
#         hlayout2 = QtWidgets.QHBoxLayout()
#
#         self.okButton = OkButtonWidget(NativeUI)
#         self.okButton.setEnabled(True)
#         self.okButton.pressed.connect(self.handle_ok_press)
#         hlayout2.addWidget(self.okButton)
#         #grid.addWidget(self.okButton, 1, 0)
#
#         self.cancelButton = CancelButtonWidget(NativeUI)
#         self.cancelButton.setEnabled(True)
#
#         hlayout2.addWidget(self.cancelButton)
#         #grid.addWidget(self.cancelButton, 1, 1)
#         vlayout = QtWidgets.QVBoxLayout()
#         vlayout.addWidget(self.label)
#         vlayout.addLayout(hlayout)
#         vlayout.addWidget(self.numberpad)
#         vlayout.addLayout((hlayout2))
#
#         self.setLayout(vlayout)
#         self.setWindowFlags(
#             QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint
#         )  # no window title
#
#     def handle_ok_press(self):
#         logging.debug(self.cha)
#         val = self.lineEdit.text()
#         self.currentWidg.setValue(float(val))
#         self.close()
#         self.currentWidg.manualChanged.emit()
#
#     def populatePopup(self, currentWidg):
#         self.currentWidg = currentWidg
#         self.label_text, self.min, self.max, self.initVal, self.step, self.decPlaces = currentWidg.label_text, currentWidg.min, currentWidg.max, currentWidg.initVal, currentWidg.step, currentWidg.decPlaces
#
#         self.label.setText(self.label_text)
#
#         self.lineEdit.setText(str(currentWidg.value()))
#
#     def handle_numberpress(self, symbol):
#         """Handle number pad button press. Put button value in line edit text, and handle inputs
#         outside accepted range or number of decimal places. Handle backspace"""
#
#         oldText = self.lineEdit.text()
#         if symbol.isnumeric() or (symbol == '.'):
#             newText = oldText + symbol
#             if float(newText) > self.max:
#                 newText = str(self.max)
#             elif float(newText) < self.min:
#                 newText = str(self.min)
#             elif '.' in newText:
#                 if len(newText.split('.')[1]) > self.decPlaces:
#                     newText = oldText
#             self.lineEdit.setText(newText)
#         elif symbol == '<':
#             self.lineEdit.setText(oldText[0:-1])
#
#     def handle_alphapress(self, symbol):
#         """Handle number pad button press. Put button value in line edit text, and handle inputs
#         outside accepted range or number of decimal places. Handle backspace"""
#
#         oldText = self.lineEdit.text()
#         if symbol.isalpha():
#             newText = oldText + symbol
#             self.lineEdit.setText(newText)
#         elif symbol == '<':
#             self.lineEdit.setText(oldText[0:-1])
#
#     def increase_button_clicked(self):
#         """Handle increase step button click"""
#         currentVal = self.get_value()
#         newVal = round(float(currentVal) + self.step, self.decPlaces)
#         if newVal >= self.max:
#             newVal = self.max
#         self.lineEdit.setText(str(newVal))
#         return 0
#
#     def decrease_button_clicked(self):
#         """Handle decrease step button click"""
#         currentVal = self.get_value()
#         newVal = round(float(currentVal) - self.step, self.decPlaces)
#         if newVal <Ftypeval= self.min:
#             newVal = self.min
#         self.lineEdit.setText(str(newVal))
#         return 0
#
#     def get_value(self):
#         return self.lineEdit.text()
