import panorama_panel

import gi
gi.require_version("Gtk", "4.0")

from gi.repository import Gtk, GLib


SECOND_PLACEHOLDERS = ("%c", "%s", "%S", "%T", "%X")


class ClockApplet(panorama_panel.Applet):
    name = "Clock"
    description = "Read the current time and date"

    def __init__(self, orientation=Gtk.Orientation.HORIZONTAL, config=None):
        super().__init__(orientation=orientation, config=config)
        if config is None:
            config = {}
        self.button = Gtk.MenuButton()
        self.button.set_has_frame(False)   # flat look
        self.label = Gtk.Label()
        self.button.set_child(self.label)

        # Create the monthly calendar
        self.popover = Gtk.Popover()
        self.calendar = Gtk.Calendar()
        self.calendar.set_show_week_numbers(True)
        self.popover.set_child(self.calendar)
        self.button.set_popover(self.popover)

        self.append(self.button)

        self.formatting = config.get("formatting", "%c")
        # Some placeholders require second precision, but not all of them. If not required,
        # use minute precision
        self.has_second_precision = any(placeholder in self.formatting for placeholder in SECOND_PLACEHOLDERS)
        self.set_time()

    def set_time(self):
        datetime = GLib.DateTime.new_now_local()
        self.label.set_text(datetime.format(self.formatting))

        if self.has_second_precision:
            current_ms = GLib.DateTime.new_now_local().get_microsecond() // 1000
            GLib.timeout_add(1000 - current_ms + 1, self.set_time)  # 1ms is added to ensure the clock is updated
        else:
            now = GLib.DateTime.new_now_local()
            current_ms = now.get_second() * 1000 + now.get_microsecond() // 1000
            GLib.timeout_add(60000 - current_ms + 1, self.set_time)
        return False   # Do not rerun the current timeout; a new one has been scheduled

    def get_config(self):
        return {"text": self.label.get_text()}
