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 GiaraClamp
from giara.single_post_stream_headerbar import SinglePostStreamHeaderbar


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, **kwargs):
        super().__init__(**kwargs)
        self.confman = ConfManager()
        self.reddit = self.confman.reddit
        self.show_multi_func = show_multi_func
        self.get_style_context().add_class('card')

        self.multis = list()
        # self.front_row = None
        self.set_sort_func(self.sort_func, None, False)
        self.set_header_func(self.separator_header_func)
        self.populate()
        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):
        # if row1 == self.front_row:
        #     return False
        # if row2 == self.front_row:
        #     return True
        return row1.get_key().lower() > row2.get_key().lower()

    def separator_header_func(self, row, prev_row):
        if (
            prev_row is not None and
            row.get_header() is None
        ):
            row.set_header(
                Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
            )

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

    def populate(self):
        self.empty()
        # self.front_row = CommonCollectionListboxRow(
        #     '',
        #     _('Front page'),
        #     lambda *args: None
        # )
        # self.add(self.front_row)
        # self.select_row(self.front_row)

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

        def cb(multi):
            self.add(MultiredditsListboxRow(multi))
            self.show_all()

        Thread(target=af).start()


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

        self.sw = Gtk.ScrolledWindow()
        self.sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        self.listbox = MultiredditsListbox(self.show_multi_func)

        self.clamp = GiaraClamp()
        self.clamp.add(self.listbox)

        self.sw.add(self.clamp)

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

        self.add(self.headerbar)
        self.headerbar.set_vexpand(False)
        self.headerbar.set_hexpand(True)
        self.add(self.sw)
        self.sw.set_vexpand(True)
