# 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/>.

"""
Dialog representing TAN input dialog for different input types
depending on configuration.
"""

from gi.repository import Adw, Gtk, GLib, Gio, GdkPixbuf
from saldo.widgets.flicker import FlickerCode


@Gtk.Template(resource_path="/org/tabos/saldo/ui/tan_dialog.ui")
class TanDialog(Adw.AlertDialog):
    __gtype_name__ = "TanDialog"

    _content_box = Gtk.Template.Child()
    _tan_entry = Gtk.Template.Child()

    def __init__(self, response, **kwargs):
        """
        Initialize TAN dialog, and show request tan mechanism
        field.
        """
        super().__init__(**kwargs)

        label = Gtk.Label(label=response.challenge)
        label.set_wrap(True)
        self._content_box.append(label)

        if getattr(response, "challenge_matrix", None):
            mime_type, data = response.challenge_matrix
            if mime_type == "image/png":
                glib_bytes = GLib.Bytes.new(data)
                stream = Gio.MemoryInputStream.new_from_bytes(glib_bytes)
                pixbuf = GdkPixbuf.Pixbuf.new_from_stream(stream, None)
                image = Gtk.Image().new_from_pixbuf(pixbuf)
                image.set_pixel_size(250)
                image.set_valign(Gtk.Align.START)
                image.set_halign(Gtk.Align.CENTER)
                self._content_box.append(image)
        elif getattr(response, "challenge_hhduc", None):
            flicker_code = FlickerCode(response.challenge_hhduc)
            self._content_box.append(flicker_code)

        self._tan_entry.grab_focus()

    @property
    def tan(self):
        return self._tan_entry.get_text()
