from plugin.twitch.utils import get_handler


class TwitchGameStreamImages(object):

    def __init__(self, context, quality="medium"):
        self.handler = get_handler(context)
        self.image_fetcher = context.services["imagefetcher"].handler
        self.images = {}
        self.quality = quality

    def get(self, stream, default=None):
        return self.images.get(self._get_image_url(stream), default)

    def connect_store(self, store):
        self.store = store
        self.store.add_listener(self)
        self.store_changed(store)

    def store_changed(self, store):
        assert store is self.store
        self._init_image_update()

    def make_getter(self):
        return lambda stream: self.get(stream)

    def _get_image_url(self, stream):
        return stream.preview[self.quality]

    def _init_image_update(self):
        image_items = []

        for stream in self.store:
            image_items.append({
                "url": self._get_image_url(stream),
                "force_reload": True
            })

        self.image_fetcher.fetch_multiple("twitch", image_items, False,
                self._update_image)

    def _update_image(self, result):
        if "image" in result and "url" in result:
            self.images[result["url"]] = result["image"]
