from gi.repository import Gtk, GLib
from threading import Thread
from giara.download_manager import download_img
from praw.exceptions import ClientException


class CustomEmoji(Gtk.Image):
    def __init__(self, subreddit, name):
        super().__init__()
        self.set_size_request(16, 16)
        self.subreddit = subreddit
        self.name = name.strip(':')
        self.load_emoji()

    def load_emoji(self):
        def af():
            try:
                url = self.subreddit.emoji[self.name].url
            except ClientException:
                print(f'Error: cannot find emoji {self.name}')
                return
            fpath = download_img(url)
            GLib.idle_add(cb, fpath)

        def cb(fpath):
            self.set_from_file(fpath)

        Thread(target=af, daemon=True).start()
