from gettext import gettext as _
from gi.repository import Gtk, GLib
from giara.single_post_stream_headerbar import SinglePostStreamHeaderbar
from threading import Thread
from praw.models import Redditor
from giara.giara_clamp import new_clamp
from giara.common_collection_listbox_row import CommonCollectionListboxRow
from giara.scrolled_win import GiaraScrolledWin
from giara.network_cache import CachedSubreddit
from giara.common_functions import get_subreddit_icon


class SubredditsListboxRow(CommonCollectionListboxRow):
    def __init__(self, subreddit, **kwargs):
        self.subreddit = subreddit
        if isinstance(subreddit, Redditor):
            self.subreddit.display_name = self.subreddit.name
            self.subreddit.display_name_prefixed = 'u/'+self.subreddit.name
            self.subreddit.title = self.subreddit.name
        super().__init__(
            self.subreddit.display_name_prefixed,
            self.subreddit.title,
            self.get_subreddit_icon,
            avatar_name=self.subreddit.display_name,
            **kwargs
        )

    def get_subreddit_icon(self):
        return get_subreddit_icon(self.subreddit)


class SubredditsListbox(Gtk.ListBox):
    def __init__(self, subreddits_gen_func, show_sub_func=None, load_now=True,
                 sort=False, **kwargs):
        super().__init__(
            margin_top=12, margin_bottom=12, vexpand=False,
            valign=Gtk.Align.START, **kwargs
        )
        self.first_refresh_done = False
        self.sort = sort
        self.get_style_context().add_class('content')
        self.subreddits_gen_func = subreddits_gen_func
        self.show_sub_func = show_sub_func
        self.subreddits = []
        self.connect('row-activated', self.on_row_activate)
        self.initialized = load_now
        self.refresh_thread = None
        if load_now:
            self.first_refresh()
        self.set_selection_mode(Gtk.SelectionMode.NONE)

    @property
    def generator(self):
        return self.subreddits_gen_func

    @generator.setter
    def generator(self, n_gen):
        self.subreddits_gen_func = n_gen

    def set_gen_func(self, gen_func):
        self.subreddits_gen_func = gen_func

    def empty(self):
        while True:
            row = self.get_row_at_index(0)
            if row:
                self.remove(row)
            else:
                break

    def refresh(self):
        self.empty()
        if self.refresh_thread is not None:
            self.refresh_thread_stop = True
            self.refresh_thread.join()
        self.refresh_thread_stop = False

        def af():
            self.subreddits = list(self.subreddits_gen_func(limit=None))
            if self.sort:
                self.subreddits.sort(key=lambda sub: sub.display_name.lower())
            for sub in self.subreddits:
                if self.refresh_thread_stop:
                    return
                subreddit = sub
                if not isinstance(sub, Redditor):
                    subreddit = CachedSubreddit(sub, sub.id)
                GLib.idle_add(cb, subreddit)
            GLib.idle_add(final_cb)

        def cb(sub):
            self.append(SubredditsListboxRow(sub))

        def final_cb():
            self.initialized = True
            self.show()

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

    def first_refresh(self):
        if self.first_refresh_done:
            return
        self.first_refresh_done = True
        self.refresh()

    def populate(self):
        for sub in self.subreddits:
            self.append(
                SubredditsListboxRow(sub)
            )
        self.show()
        self.initialized = True

    def on_row_activate(self, lb, row):
        if self.show_sub_func is not None:
            self.show_sub_func(row.subreddit)


class SubredditsListView(Gtk.Box):
    def __init__(self, subreddits_gen_func, show_sub_func,
                 sort=False, load_now=True):
        super().__init__(orientation=Gtk.Orientation.VERTICAL)
        self.subreddits_gen_func = subreddits_gen_func
        self.show_sub_func = show_sub_func

        self.sw = GiaraScrolledWin()
        self.listbox = SubredditsListbox(
            self.subreddits_gen_func, self.show_sub_func, sort=sort,
            load_now=load_now
        )

        self.clamp = new_clamp()
        self.clamp.set_child(self.listbox)

        self.sw.set_child(self.clamp)

        self.headerbar = SinglePostStreamHeaderbar(_('Subreddits'))
        self.headerbar.refresh_btn.connect(
            'clicked',
            lambda *args: self.refresh()
        )

        self.append(self.headerbar)
        self.append(self.sw)

    def refresh(self):
        self.listbox.refresh()

    def first_refresh(self):
        self.listbox.first_refresh()
