# 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, Gdk, Gio, Secret

from gettext import gettext as _

from passbook.define import App


# Broken, signals from headerbar not working
# @Gtk.Template.from_resource
class UnlockDialog:
    """
        Dialog to unlock a collection
    """

    def __init__(self, uri, transient):
        """
            Init dialog
            @param uri as str
        """
        self.__uri = uri
        self.__kp = None
        builder = Gtk.Builder()
        builder.add_from_resource(
            "/org/gnome/Passbook/UnlockDialog.ui")
        builder.connect_signals(self)
        self.__dialog = builder.get_object("dialog")
        self.__dialog.set_transient_for(transient)
        self.__label = builder.get_object("label")
        self.__label.set_text(_("Enter password for this collection :"))
        self.__password_entry = builder.get_object("password_entry")
        self.__save_button = builder.get_object("save_button")
        self.__unlock_button = builder.get_object("unlock_button")
        self.__dialog.set_transient_for(App().window)

    def run(self):
        """
            Run dialog
            @return pykeepass.pykeepass.PyKeePass
        """
        self.__dialog.run()
        if self.__kp is not None and self.__save_button.get_active():
            schema_string = _("Keepass password for %s") % self.__uri
            SecretSchema = {
                "type": Secret.SchemaAttributeType.STRING,
                "uri": Secret.SchemaAttributeType.STRING
            }
            SecretAttributes = {
                "type": "Passbook keepass password",
                "uri": self.__uri
            }
            schema = Secret.Schema.new("org.gnome.Passbook",
                                       Secret.SchemaFlags.NONE,
                                       SecretSchema)
            Secret.password_store(schema, SecretAttributes,
                                  Secret.COLLECTION_DEFAULT,
                                  schema_string,
                                  self.__password_entry.get_text(),
                                  None,
                                  None)
        self.__dialog.destroy()
        return self.__kp

#######################
# PROTECTED           #
#######################
    def _on_key_release_event(self, entry, event):
        """
            Update button visibility and set default response on Enter
            @param entry as Gtk.Entry
            @param event as Gdk.Event
        """
        if event.keyval in [Gdk.KEY_Return, Gdk.KEY_KP_Enter]:
            self.__unlock_button.clicked()

    def _on_response(self, dialog, response_id):
        """
            Unlock collection
            @param dialog as Gtk.Dialog
            @param response_id as int
        """
        if response_id in [Gtk.ResponseType.CANCEL,
                           Gtk.ResponseType.DELETE_EVENT]:
            return

    def _on_cancel_clicked(self, button):
        """
            Close dialog
            @param button as Gtk.Button
        """
        self.__dialog.response(Gtk.ResponseType.CANCEL)

    def _on_unlock_clicked(self, button):
        """
            Unlock collection
            @param button as Gtk.Button
        """
        from pykeepass import PyKeePass
        try:
            f = Gio.File.new_for_uri(self.__uri)
            try:
                self.__kp = PyKeePass(
                                f.get_path(),
                                password=self.__password_entry.get_text())
            except:
                self.__kp = PyKeePass(f.get_path(), password="")
                self.__kp.password = self.__password_entry.get_text()
                self.__kp.save()
            self.__dialog.response(Gtk.ResponseType.OK)
        except:
            self.__label.set_text(_("Invalid password !"))

#######################
# PRIVATE             #
#######################
