from typing import Any, Self

from gi.repository import Adw, Gdk, Gio, GObject, Gtk

from morphosis.config import PREFIX


@Gtk.Template(resource_path=f"{PREFIX}/drop-overlay.ui")
class DropOverlay(Adw.Bin):
    """A drop overlay using a Gtk.FileFilter."""

    __gtype_name__ = "DropOverlay"

    filter = GObject.Property(type=Gtk.FileFilter)
    content = GObject.Property(type=Gtk.Widget)

    drop = GObject.Signal(arg_types=(Gio.File,))

    @Gtk.Template.Callback()
    def _filter(self, drop_target: Gtk.DropTarget, *_args: Any) -> None:
        if not isinstance(file := drop_target.props.value, Gio.File):
            return

        file_info = file.query_info(
            "standard::display-name,standard::content-type",
            Gio.FileQueryInfoFlags.NONE,
        )

        if not self.filter.match(file_info):
            drop_target.reject()

    @Gtk.Template.Callback()
    def _drop(
        self,
        _drop_target: Gtk.DropTarget,
        file: Gio.File,
        *_args: Any,
    ) -> bool:
        self.emit("drop", file)
        return True

    @Gtk.Template.Callback("bool")
    def _bool(self, _win: Self, current_drop: Gdk.Drop) -> bool:
        return bool(current_drop)


# https://gitlab.gnome.org/GNOME/gtk/-/issues/7785
DropOverlay.set_css_name("drop-overlay")
