# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
from qgis.PyQt.QtCore import QTime
from qgis.PyQt.QtWidgets import QTimeEdit


class QTimeEdit15Step(QTimeEdit):
    def stepBy(self, steps):
        current = self.time()
        minutes = current.hour() * 60 + current.minute() + steps * 15
        minutes = max(0, min(24 * 60 - 1, minutes))
        new_time = QTime(minutes // 60, minutes % 60)
        self.setTime(new_time)


class QTimeEdit24Step(QTimeEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._show_24 = False

    def stepBy(self, steps):
        current = self.time()
        minutes = current.hour() * 60 + current.minute() + steps * 15
        # Clamp to valid range
        minutes = max(0, min(24 * 60, minutes))
        if minutes == 24 * 60:
            self.setTime(QTime(0, 0))
            self._show_24 = True
        else:
            self.setTime(QTime(minutes // 60, minutes % 60))
            self._show_24 = False

    def textFromDateTime(self, datetime):
        t = datetime.time()
        if t.hour() == 0 and t.minute() == 0 and self._show_24:
            return "24:00"
        return t.toString("HH:mm")

    def setTime24(self, time):
        if time.hour() == 24 and time.minute() == 0:
            self.setTime(QTime(0, 0))
            self._show_24 = True
        else:
            self.setTime(time)
            self._show_24 = False
