from giara.constants import RESOURCE_PREFIX
from gettext import gettext as _
from gi.repository import Gtk, GLib
from giara.path_utils import is_image
from giara.download_manager import download_img
from threading import Thread
from giara.confManager import ConfManager
from giara.time_utils import humanize_utc_timestamp
from giara.simple_avatar import SimpleAvatar


class UserHeading(Gtk.Box):
    def __init__(self, user, refresh_func, **kwargs):
        super().__init__(**kwargs)
        self.confman = ConfManager()
        self.reddit = self.confman.reddit
        self.user = user
        self.refresh_func = refresh_func
        self.builder = Gtk.Builder.new_from_resource(
            f'{RESOURCE_PREFIX}/ui/redditor_heading.ui'
        )
        self.main_box = self.builder.get_object('main_box')
        self.avatar_container = self.builder.get_object('avatar_container')
        self.name_label = self.builder.get_object('name_label')
        self.name_label.set_text(self.user.name)
        self.follow_btn = self.builder.get_object('follow_btn')
        self.follow_btn.connect('clicked', self.follow_or_unfollow)
        self.refresh_follow_btn()
        self.karma_label = self.builder.get_object('karma_label')
        self.karma_label.set_text(str(self.user.total_karma))
        self.cakeday_label = self.builder.get_object('cakeday_label')
        self.cakeday_label.set_text(str(
            humanize_utc_timestamp(self.user.created_utc).split('\n')[0]
        ))

        self.avatar = SimpleAvatar(
            64,
            self.user.name,
            self.get_user_icon
        )
        self.avatar_container.append(self.avatar)

        self.append(self.main_box)

    def refresh_follow_btn(self, *args):
        sub = self.reddit.subreddit('u_'+self.user.name)
        follow_style_context = self.follow_btn.get_style_context()
        for c in ('suggested-action', 'destructive-action'):
            follow_style_context.remove_class(c)
        if sub.user_is_subscriber:
            follow_style_context.add_class('destructive-action')
            self.follow_btn.set_label(_('Unfollow'))
        else:
            follow_style_context.add_class('suggested-action')
            self.follow_btn.set_label(_('Follow'))

    def follow_or_unfollow(self, *args):
        self.follow_btn.set_sensitive(False)

        def af():
            sub = self.reddit.subreddit('u_'+self.user.name)
            if sub.user_is_subscriber:
                sub.unsubscribe()
            else:
                sub.subscribe()
            GLib.idle_add(cb)

        def cb():
            self.refresh_func()

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

    def get_user_icon(self):
        if is_image(self.user.icon_img):
            return download_img(self.user.icon_img)
