from giara.constants import RESOURCE_PREFIX
from gettext import gettext as _
from gi.repository import Gtk
from giara.search_view import CommonSearchView
from giara.sections_stack import SectionsStack


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(title)

        self.sections_stack = SectionsStack(
            [{
                'name': f'search_{self.subreddit.display_name}',
                'title': title,
                'gen': None,
                'load_now': False
            }],
            self.show_post_func,
            load_now=False
        )
        self.add(self.sections_stack)
        self.sections_stack.set_vexpand(True)

    def on_search_activate(self, *args):
        term = self.search_entry.get_text()
        lbox = self.sections_stack.get_children()[0].post_preview_lbox
        lbox.stop_loading = True
        while lbox.loading:
            while Gtk.events_pending():
                Gtk.main_iteration()
        lbox.set_gen_func(
            lambda *args, **kwargs: self.subreddit.search(
                term, *args, **kwargs
            )
        )
        self.sections_stack.refresh()
