from giara.constants import RESOURCE_PREFIX
from gettext import gettext as _
from gi.repository import Gtk, GLib
from giara.search_view import CommonSearchView
from giara.sections import PostListSection
from giara.ellipsized_label import make_ellipsized_label
from threading import Thread
from time import sleep


class SubredditSearchView(CommonSearchView):
    def __init__(self, subreddit, show_post_func, **kwargs):
        self.headerbar_builder = Gtk.Builder.new_from_resource(
            f'{RESOURCE_PREFIX}/ui/post_details_headerbar.ui'
        )
        super().__init__(
            self.headerbar_builder.get_object('headerbar'),
            **kwargs
        )
        self.subreddit = subreddit
        self.show_post_func = show_post_func
        self.headerbar.back_btn = self.headerbar_builder.get_object(
            'back_btn'
        )
        self.headerbar.refresh_btn = self.headerbar_builder.get_object(
            'refresh_btn'
        )

        title = _('Searching in {0}').format(
            self.subreddit.display_name_prefixed
        )
        self.headerbar.set_title_widget(make_ellipsized_label(title))

        self.posts_section = PostListSection(
            None, self.show_post_func, load_now=False
        )
        self.append(self.posts_section)

    def on_search_activate(self, *args):
        term = self.search_entry.get_text()
        lbox = self.posts_section.listview
        lbox.stop_loading = True

        def af():
            while lbox.loading:
                sleep(1)
            GLib.idle_add(cb)

        def cb():
            lbox.set_gen_func(
                lambda *args, **kwargs: self.subreddit.search(
                    term, *args, **kwargs
                )
            )
            lbox.refresh()

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