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


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

    def __init__(self, builder, section, view_switcher=True, sort_menu=False,
                 sorting_methods=dict(), default_method=None, stack=None):
        super().__init__(hexpand=True, vexpand=False)
        self.confman = ConfManager()
        self.reddit = self.confman.reddit
        self.builder = builder
        self.section = section
        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.section, sorting_methods, default_method
            )
            self.headerbar.pack_end(self.sort_btn)
        if view_switcher and stack is not None:
            self.squeezer = self.builder.get_object('squeezer')
            self.view_switcher = Adw.ViewSwitcher(
                valign=Gtk.Align.FILL, stack=stack,
                policy=Adw.ViewSwitcherPolicy.WIDE
            )
            # self.view_switcher.set_policy(Adw.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.set_child(self.headerbar)
