from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import StringProperty
from kivy.uix.stacklayout import StackLayout
from kivy.clock import Clock, mainthread
from ..lock import Lock

monitor_lock = Lock("monitor")

def to_status(v):
    if v is None:
        return "No dev"
    elif isinstance(v, bool):
        if v:
            return "OK    "
        else:
            return "Not OK"
    else:
        return "{: <6}".format(v[0:6])

class Monitor(RelativeLayout):
    messages = StringProperty("")
    devices_alive = StringProperty("")


    def __init__(self, **kwargs):
        super(Monitor, self).__init__(**kwargs)
        Clock.schedule_interval(self.update_monitor, 30)
        Clock.schedule_once(self.update_monitor)

    @mainthread
    def update_monitor(self, dt):
        if self.parent is None or 'Mapping' not in self.parent.ids:
            return True

        status_commands = self.parent.ids['Mapping'].monitor_commands
        messages = []
        for command in status_commands:
            response = command()
            if response is not None:
                # FIXME: use second item of the response to know when it
                # should update status
                messages += response[0]
        with monitor_lock:
            self.messages = "\n".join(messages)

        usb_devices = self.parent.ids['Mapping'].monitor_usb_devices
        status_check = {k: to_status(v()) for (k, v) in usb_devices.items()}
        with monitor_lock:
            self.devices_alive = "    ".join([f"{k}: {v}" for (k, v) in status_check.items()])
