# Copyright (c) 2014-2018 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from gi.repository import Gtk

from gettext import gettext as _


class LabelRow(Gtk.ListBoxRow):
    """
        A row with label + delete button
    """

    def __init__(self, collection, group, show_delete):
        """
            Init label
            @param collection as KeepassCollection
            @param group as pykeepass.group
            @param show_delete as bool => Allow group deletion
        """
        Gtk.ListBoxRow.__init__(self)
        self.__collection = collection
        self.__group = group
        self.__path = _("All") if group.path == "/" else group.path
        split = self.__path.split("/")
        if len(split) == 1:
            spaces = ""
            name = self.__path
        else:
            spaces = "      " * (len(split) - 1) + "↳ "
            name = "".join(split[-1])
        grid = Gtk.Grid()
        grid.show()
        label = Gtk.Label.new()
        label.set_text(spaces + name)
        label.set_property("halign", Gtk.Align.START)
        label.show()
        grid.add(label)
        if group.path != "/" and show_delete:
            button = Gtk.Button.new_from_icon_name("user-trash-symbolic",
                                                   Gtk.IconSize.MENU)
            button.get_style_context().add_class("menu-button")
            button.show()
            button.set_hexpand(True)
            button.set_property("halign", Gtk.Align.END)
            button.connect("clicked", self.__on_delete_button_clicked)
            grid.add(button)
        self.add(grid)

    @property
    def group(self):
        """
            Get group
            @return pykeepass.group
        """
        return self.__group

#######################
# PRIVATE             #
#######################
    def __on_delete_button_clicked(self, button):
        """
            Delete group
            @param button as Gtk.Button
        """
        if not button.get_style_context().has_class("menu-button-destructive"):
            button.get_style_context().remove_class("menu-button")
            button.get_style_context().add_class("menu-button-destructive")
            return
        self.group.delete()
        self.__collection.save()
        self.destroy()


class GroupsPopover(Gtk.Popover):
    """
        Allow group selection and entry completion
    """

    def __init__(self, collection, entry):
        """
            Init popover
            @param as KeepassCollection
            @param entry as Gtk.Entry
        """
        Gtk.Popover.__init__(self)
        self.__entry = entry
        self.set_size_request(250, 250)
        listbox = Gtk.ListBox()
        listbox.set_selection_mode(Gtk.SelectionMode.NONE)
        listbox.connect("row-activated", self.__on_row_activated)
        listbox.get_style_context().add_class("theme-background")
        listbox.show()
        scrolled = Gtk.ScrolledWindow()
        scrolled.set_margin_start(2)
        scrolled.set_margin_end(2)
        scrolled.set_margin_top(2)
        scrolled.set_margin_right(2)
        scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        scrolled.add(listbox)
        scrolled.show()
        self.add(scrolled)
        groups = collection.kp.groups
        completion = entry.get_completion()
        for group in groups:
            label = LabelRow(collection, group, completion is None)
            label.show()
            listbox.add(label)
        if not groups:
            label = Gtk.Label.new(_("No groups available"))
            label.set_property("halign", Gtk.Align.START)
            label.show()
            listbox.add(label)
            listbox.set_sensitive(False)

#######################
# PRIVATE             #
#######################
    def __on_row_activated(self, listbox, row):
        """
            Complete entry
            @param listbox as Gtk.ListBox
            @param row as Gtk.ListBoxRow
        """
        value = row.group.path
        if value == "/":
            value = ""
        self.__entry.set_text(value)
        self.popdown()
