from gi.repository import Adw, GObject, Gtk

from iotas.text_utils import sanitise_path


@Gtk.Template(resource_path="/org/gnome/World/Iotas/ui/editor_rename_header_bar.ui")
class EditorRenameHeaderBar(Adw.Bin):
    __gtype_name__ = "EditorRenameHeaderBar"
    __gsignals__ = {
        "cancelled": (GObject.SignalFlags.RUN_FIRST, None, ()),
        "renamed": (GObject.SignalFlags.RUN_FIRST, None, (str,)),
    }

    _entry = Gtk.Template.Child()
    _apply_button = Gtk.Template.Child()

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

    def enter(self, title: str) -> None:
        """Start renaming.

        :param str title: Existing title
        """
        self._entry.set_text(title)
        self._entry.grab_focus()
        self._entry.set_position(-1)

    def focus(self) -> None:
        """Grab focus to entry."""
        self._entry.grab_focus()

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

    @Gtk.Template.Callback()
    def _abort_rename(self, _button: Gtk.Button) -> None:
        self.emit("cancelled")

    @Gtk.Template.Callback()
    def _on_entry_changed(self, _entry: Gtk.Editable) -> None:
        self._apply_button.set_sensitive(self.__entry_valid())

    @Gtk.Template.Callback()
    def _on_entry_activated(self, _entry: Gtk.Entry) -> None:
        if self.__entry_valid():
            self.__apply_rename()

    def __apply_rename(self) -> None:
        self.emit("renamed", self.__get_sanitised_entry())

    def __entry_valid(self) -> None:
        return self.__get_sanitised_entry() != ""

    def __get_sanitised_entry(self) -> str:
        new_title = self._entry.get_text().strip()
        return sanitise_path(new_title)
