from django.utils import timezone as tz

from aircox.models import Station
from .streamer import Streamer

__all__ = ("Streamers",)


class Streamers:
    """Keep multiple streamers in memory, allow fetching informations."""

    streamers = None
    """Stations by station id."""
    streamer_class = Streamer
    timeout = None
    """Timedelta to next update."""
    next_date = None
    """Next update datetime."""

    def __init__(self, timeout=None, streamer_class=streamer_class):
        self.timeout = timeout or tz.timedelta(seconds=2)

    def reset(self, stations=Station.objects.active()):
        # FIXME: cf. TODO in aircox.controllers about model updates
        stations = stations.all()
        self.streamers = {station.pk: self.streamer_class(station) for station in stations}

    def fetch(self):
        """Call streamers fetch if timed-out."""
        if self.streamers is None:
            self.reset()

        now = tz.now()
        if self.next_date is not None and now < self.next_date:
            return

        for streamer in self.streamers.values():
            streamer.fetch()
        self.next_date = now + self.timeout

    def get(self, key, default=None):
        return self.streamers.get(key, default)

    def values(self):
        return self.streamers.values()

    def __len__(self):
        return self.streamers and len(self.streamers) or 0

    def __getitem__(self, key):
        return self.streamers[key]

    def __contains__(self, key):
        """Key can be a Station or a Station id."""
        if isinstance(key, Station):
            return key.pk in self.streamers
        return key in self.streamers

    def __iter__(self):
        return self.streamers.values() if self.streamers else iter(tuple())
