from src import logger
from PyQt6 import QtWidgets, QtCore
from PyQt6.QtCore import QDate
from PyQt6.QtGui import QColor, QPen
from src.backend import Database
import darkdetect

color = "#ddfb00" if darkdetect.isDark() else "#2204ff"
pen = QPen(QColor(color))
pen.setWidth(5)


class MessageCalendar(QtWidgets.QCalendarWidget):
    # Widget for MessageCalendar
    def __init__(self, parent=None):
        super().__init__(parent)
        self.messages = {}  # Dictionary to store dates with messages
        self.setFirstDayOfWeek(QtCore.Qt.DayOfWeek.Monday)
        self.setGridVisible(True)
        self.getMessages()

    def getMessages(self):
        # Get the messages from the database
        messages = Database().getAllMessages()
        logger.debug("Got {} messages", len(messages))
        self.setMessages(messages)

    def deleteMessage(self, id):
        message = [message for message in self.messages if message["id"] == id][0]
        self.messages.remove(message)
        self.updateCells()

    def setMessages(self, messages):
        # remove all drawn circles

        for message in messages:
            # print(message)
            # Convert the date string to a QDate object
            date = QDate.fromString(message["remind_at"], "yyyy-MM-dd")
            # Store the message for the date
            self.messages[date] = message["message"]
        self.updateCells()

    def updateCells(self):
        self.repaint()

    def paintCell(self, painter, rect, date):
        super().paintCell(painter, rect, date)

        # Check if there is a message for the current date
        if date in self.messages:
            # draw a circle below the date
            painter.setPen(pen)
            # increase draw size
            bl = rect.bottomLeft()
            bl.setX(bl.x() + 8)
            bl.setY(bl.y() - 8)
            painter.drawEllipse(bl, 5, 5)
        else:
            for cell in self.messages:
                if cell.month() == date.month() and cell.year() == date.year():
                    # draw a circle below the date
                    painter.setPen(QPen(QtCore.Qt.GlobalColor.transparent))
                    bl = rect.bottomLeft()
                    bl.setX(bl.x() + 8)
                    bl.setY(bl.y() - 8)
                    painter.drawEllipse(bl, 5, 5)

    def reload(self, date):
        qdate = QDate.fromString(date, "yyyy-MM-dd")
        del self.messages[qdate]
        self.updateCells()

    # def change_stylesheet_cell(self, date: QDate, color: str):
    #     # change the stylesheet of a cell
    #     self.setStyleSheet(
    #         f"QCalendarWidget QTableView QTableCornerButton::section {{background-color: {color};}}"
    #     )
