from gettext import gettext as _
from gi.repository import Gtk, Gio, GLib


class SortingMenuButton(Gtk.MenuButton):
    def __init__(self, target_view, methods, default_method=None, **kwargs):
        super().__init__(**kwargs)
        self.methods = methods
        if default_method is None:
            default_method = list(self.methods.keys())[0]
        self.target_view = target_view
        self.main_box = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL, spacing=6
        )
        self.icon = Gtk.Image.new_from_icon_name(
            self.methods[default_method]['icon']
        )
        self.main_box.append(self.icon)
        self.main_box.append(Gtk.Image.new_from_icon_name(
            'pan-down-symbolic'
        ))
        self.get_first_child().set_child(self.main_box)
        # self.set_icon_name(self.methods[default_method]['icon'])
        self.create_action(self.methods, default_method)
        self.popover = Gtk.PopoverMenu.new_from_model(
            self.methods_to_menu_model(self.methods)
        )
        self.set_popover(self.popover)

        self.old_sorting = None
        self.set_sorting(default_method)

    def methods_to_menu_model(self, methods: dict):
        items = '\n'.join([
            f'''<item>
            <attribute name="label">{methods[m]['name']}</attribute>
            <attribute name="action">sort.change</attribute>
            <attribute name="target">{m}</attribute>
            </item>''' for m in methods.keys()
        ])
        return Gtk.Builder.new_from_string(
            f'''<?xml version="1.0" encoding="UTF-8"?>
                <interface><menu id="sort-menu"><section>
                    {items}
                </section></menu></interface>
            ''', -1
        ).get_object('sort-menu')

    def create_action(self, methods: dict, default_method: str) -> None:
        self.sort_action_group = Gio.SimpleActionGroup()
        sm_action = Gio.SimpleAction.new_stateful(
            'change',
            GLib.VariantType.new('s'),
            GLib.Variant('s', default_method)
        )
        sm_action.connect('activate', self.on_sort_action_activated)
        self.sort_action_group.add_action(sm_action)
        self.insert_action_group('sort', self.sort_action_group)

    def on_sort_action_activated(self, action: Gio.SimpleAction,
                                 target: GLib.Variant, *args):
        self.popover.popdown()
        action.change_state(target)
        n_sorting = str(target).strip("'")
        if n_sorting == self.old_sorting:
            return
        self.set_sorting(n_sorting)

    def set_sorting(self, n_sorting):
        self.old_sorting = n_sorting
        self.icon.set_from_icon_name(
            self.methods[n_sorting]['icon']
        )
        self.set_tooltip_text(_('Sort by: {0}').format(
            self.methods[n_sorting]['name']
        ))
        self.target_view.set_gen_func(
            getattr(self.target_view.source, n_sorting)
        )
        self.target_view.refresh()
