import datetime

from kivy.uix.label import Label
from kivy.properties import NumericProperty, StringProperty, \
    ObjectProperty, AliasProperty
from kivy.clock import Clock

from signage.fader import NodeBehavior


class ClockNode(NodeBehavior, Label):
    update_interval = NumericProperty(1.0)
    format = StringProperty("%H:%M")
    now = ObjectProperty(None)

    def get_text(self):
        if self.now and self.format:
            return self.now.strftime(self.format)
        return ''

    text = AliasProperty(get_text, bind=['now', 'format'])

    _interval = None

    def __init__(self, **kwargs):
        super(ClockNode, self).__init__(**kwargs)
        self.on_update_interval(None, self.update_interval)
        self.update_clock()

    def on_update_interval(self, instance, value):
        if self._interval:
            self._interval.cancel()
        self._interval = Clock.schedule_interval(self.update_clock, value)

    def update_clock(self, dt=None):
        self.now = datetime.datetime.now()
