from gettext import gettext as _
from gi.repository import Gtk, GLib
from giara.confManager import ConfManager
from giara.download_manager import download_img
from giara.path_utils import is_image
from threading import Thread
from giara.common_collection_listbox_row import CommonCollectionListboxRow
from giara.giara_clamp import new_clamp
from giara.single_post_stream_headerbar import SinglePostStreamHeaderbar
from giara.scrolled_win import GiaraScrolledWin


class MultiredditsListboxRow(CommonCollectionListboxRow):
    def __init__(self, multi, **kwargs):
        self.multi = multi
        super().__init__(
            '',
            self.multi.display_name,
            self.get_icon,
            **kwargs
        )

    def get_icon(self, *args):
        if is_image(self.multi.icon_url):
            return download_img(self.multi.icon_url)

    def get_key(self):
        return self.multi.display_name.lower()


class MultiredditsListbox(Gtk.ListBox):
    def __init__(self, show_multi_func=None, load_now=True, **kwargs):
        super().__init__(
            margin_top=12, margin_bottom=12, vexpand=False,
            valign=Gtk.Align.START, **kwargs
        )
        self.first_refresh_done = False
        self.confman = ConfManager()
        self.reddit = self.confman.reddit
        self.show_multi_func = show_multi_func
        self.get_style_context().add_class('content')

        self.multis = list()
        # self.front_row = None
        self.set_sort_func(self.sort_func, None, False)
        if load_now:
            self.first_refresh()
        self.set_selection_mode(Gtk.SelectionMode.NONE)
        self.connect('row-activated', self.on_row_activate)

    def on_row_activate(self, lb, row):
        if row.multi is not None and self.show_multi_func is not None:
            self.show_multi_func(row.multi)

    def sort_func(self, row1, row2, data, notify_destroy):
        return row1.get_key().lower() > row2.get_key().lower()

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

    def populate(self):
        self.empty()

        def af():
            self.multis = self.reddit.user.multireddits()
            for multi in self.multis:
                multi._fetch()
                GLib.idle_add(cb, multi)

        def cb(multi):
            self.append(MultiredditsListboxRow(multi))
            self.show()

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

    def refresh(self):
        self.populate()

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


class MultiredditsListView(Gtk.Box):
    def __init__(self, show_multi_func, load_now=True, **kwargs):
        super().__init__(orientation=Gtk.Orientation.VERTICAL, **kwargs)
        self.show_multi_func = show_multi_func

        self.sw = GiaraScrolledWin()
        self.listbox = MultiredditsListbox(
            self.show_multi_func, load_now=load_now
        )

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

        self.sw.set_child(self.clamp)

        self.headerbar = SinglePostStreamHeaderbar(_('Multireddits'))
        self.headerbar.refresh_btn.connect(
            'clicked',
            lambda *args: self.listbox.populate()
        )

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

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

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