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

from iotas.formatter import LinkStateInfo


@Gtk.Template(resource_path="/org/gnome/World/Iotas/ui/link_dialog.ui")
class LinkDialog(Adw.Dialog):
    """Link editing/creating dialog."""

    __gtype_name__ = "LinkDialog"

    __gsignals__ = {
        "apply": (GObject.SignalFlags.RUN_FIRST, None, (LinkStateInfo,)),
    }

    _url_entry = Gtk.Template.Child()
    _text_entry = Gtk.Template.Child()
    _button = Gtk.Template.Child()

    def __init__(self) -> None:
        super().__init__()

        action_group = Gio.SimpleActionGroup.new()
        app = Gio.Application.get_default()

        action = Gio.SimpleAction.new("submit")
        action.connect("activate", lambda _a, _p: self.__apply())
        action_group.add_action(action)
        app.set_accels_for_action("link-dialog.submit", ["<Alt>Return"])

        app.get_active_window().insert_action_group("link-dialog", action_group)
        self.__action_group = action_group

        self.connect("closed", lambda _o: self.__cleanup())

    def show(self, info: LinkStateInfo, window: Gtk.Window) -> None:
        """Show dialog.

        :param LinkStateInfo info: Link state in buffer
        :param Gtk.Window window: Parent window
        """
        if info.creating:
            # Translators: Title
            title = _("Insert Link")
            # Translators: Button
            button_label = _("Create")
        else:
            # Translators: Title
            title = _("Edit Link")
            # Translators: Button
            button_label = _("Apply")
        self._url_entry.set_text(info.link)
        self._text_entry.set_text(info.text)
        self.set_title(title)
        self._button.set_label(button_label)
        self.__info = info

        for action in self.__action_group.list_actions():
            self.__action_group.lookup_action(action).set_enabled(True)

        self.present(window)

        # Can't directly call grab_focus from idle_add otherwise its returning of True will retain,
        # and repeat, the event
        def focus_url_entry():
            self._url_entry.grab_focus()

        GLib.idle_add(focus_url_entry)

    @Gtk.Template.Callback()
    def _on_url_activated(self, _entry: Gtk.Entry) -> None:
        self._text_entry.grab_focus()

    @Gtk.Template.Callback()
    def _on_text_activated(self, _entry: Gtk.Entry) -> None:
        self.__apply()

    @Gtk.Template.Callback()
    def _on_button_clicked(self, _button: Gtk.Button) -> None:
        self.__apply()

    def __apply(self) -> None:
        self.__info.link = self._url_entry.get_text()
        self.__info.text = self._text_entry.get_text()
        self.emit("apply", self.__info)
        self.close()

    def __cleanup(self) -> None:
        for action in self.__action_group.list_actions():
            self.__action_group.lookup_action(action).set_enabled(False)
