# Copyright (c) 2020-2022 Jan-Michael Brummer <jan.brummer@tabos.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


@Gtk.Template(resource_path="/org/tabos/saldo/ui/change_password_dialog.ui")
class ChangePasswordDialog(Gtk.Dialog):
    __gtype_name__ = "ChangePasswordDialog"

    _current_password_entry = Gtk.Template.Child()
    _new_password_entry = Gtk.Template.Child()
    _confirm_password_entry = Gtk.Template.Child()
    _change_button = Gtk.Template.Child()

    def __init__(self, backend, **kwargs):
        super().__init__(**kwargs)

        self._backend = backend
        self._change_button.set_sensitive(False)

        self._new_password_entry.connect("changed", self._on_password_entry_changed)
        self._confirm_password_entry.connect("changed", self._on_password_entry_changed)
        self._change_button.add_css_class("suggested-action")
        self._change_button.connect("clicked", self._on_change_button_clicked)

    def _on_change_button_clicked(self, _):
        self._backend.change_safe_password(
            self._current_password_entry.get_text(), self._new_password_entry.get_text()
        )
        self.destroy()

    # @Gtk.Template.Callback()
    def _on_password_entry_changed(self, _):
        # Validate new and confirmed password
        current_password = self._current_password_entry.get_text()
        new_password = self._new_password_entry.get_text()
        confirm_password = self._confirm_password_entry.get_text()

        if (
            len(new_password) > 3
            and new_password != current_password
            and new_password == confirm_password
        ):
            self._change_button.set_sensitive(True)
        else:
            self._change_button.set_sensitive(False)
