from .widget_sources.Ui_calendar_entry import Ui_Dialog
from PyQt6 import QtWidgets
from PyQt6.QtCore import pyqtSignal
from src.backend.database import Database
from src import Icon


class CalendarEntry(QtWidgets.QDialog, Ui_Dialog):
    deleteSignal = pyqtSignal(
        int
    )  # when emit, send the id of the message to be deleted
    repaintSignal = pyqtSignal(str)

    def __init__(self, parent=None, messages=None, date=None):
        super().__init__(parent)
        self.setupUi(self)
        self.messages = messages
        self.spin_select_message.setMaximum(len(self.messages))
        self.spin_select_message.setMinimum(1)
        self.spin_select_message.setValue(1)
        self.spin_select_message.setWrapping(True)
        self.date = date
        self.set_message()
        self.spin_select_message.valueChanged.connect(self.set_message)
        Icon("close", self.btn_close)
        self.btn_delete_message.clicked.connect(self.delete_message)
        self.btn_close.clicked.connect(self.close)

    def __get_id(self, message):
        for i in range(len(self.messages)):
            if self.messages[i] == message:
                return self.messages[i]["id"]

    def __message_index(self, id):
        for i in range(len(self.messages)):
            if self.messages[i]["id"] == id:
                return i

    def delete_message(self):
        value = self.spin_select_message.value()
        # print(value)
        if value > 0:
            value = value - 1
            message = self.messages[value]
            id = self.__get_id(message)
            # print("id", id)
            # del self.messages[value - 1]
            self.spin_select_message.setMaximum(len(self.messages))
            self.message_box.clear()
            self.set_message()

            Database().deleteMessage(id)
            self.messages.pop(self.__message_index(id))
            if len(self.messages) == 0:
                self.repaintSignal.emit(self.date)
                self.close()
        else:
            #
            self.repaintSignal.emit()
            self.close()

    def set_message(self):
        value = self.spin_select_message.value()
        if value < 1:
            return
        message = self.messages[value - 1]
        appnr = message["appnr"]
        text = message["message"]
        if appnr is not None:
            self.line_app_info.setText(str(appnr))
        else:
            self.line_app_info.setText("/")
        self.message_box.setText(text)
        self.message_box.repaint()


def launch_calendar_entry():
    messages = Database().getMessages("2024-06-10")

    app = QtWidgets.QApplication([])
    dialog = CalendarEntry(messages=messages)
    dialog.show()
    app.exec()
