from gi.repository import Gtk, Handy, GObject
from giara.confManager import ConfManager
from giara.sort_menu_btn import SortingMenuButton


class SqueezingViewSwitcherHeaderbar(Handy.WindowHandle):
    __gsignals__ = {
       'squeeze': (
           GObject.SignalFlags.RUN_FIRST,
           None,
           (bool,)
        )
    }

    def __init__(self, builder, stack, view_switcher=True, sort_menu=False,
                 sorting_methods=dict(), default_method=None, **kwargs):
        super().__init__(**kwargs)
        self.confman = ConfManager()
        self.reddit = self.confman.reddit
        self.builder = builder
        self.stack = stack
        self.headerbar = self.builder.get_object('headerbar')

        if sort_menu:
            if default_method == 'from_conf':
                default_method = self.confman.conf['default_front_page_view']
            self.sort_btn = SortingMenuButton(
                self.stack, sorting_methods, default_method
            )
            self.headerbar.pack_end(self.sort_btn)
        if view_switcher:
            self.squeezer = self.builder.get_object('squeezer')
            self.view_switcher = Handy.ViewSwitcher()
            self.view_switcher.set_policy(Handy.ViewSwitcherPolicy.AUTO)
            self.squeezer.add(self.view_switcher)
            self.squeezer.add(Gtk.Label())
            self.squeezer.connect(
                'notify::visible-child',
                lambda *args: self.emit(
                    'squeeze',
                    self.squeezer.get_visible_child() != self.view_switcher
                )
            )
            self.view_switcher.set_valign(Gtk.Align.FILL)
            self.view_switcher.set_stack(self.stack)

        self.add(self.headerbar)
