# widgets/loadingoverlay.py
#
# Copyright 2020-2025 Fabio Comuni, et al.
#
# 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 gettext import gettext as _

from gi.repository import Gtk
from gi.repository import Adw


def LoadingOverlay(cancellable, label=None):
    """
    This used to be a Class, but, again, Adw.Toast is final.
    Is a Toast that cancell the `cancellable` clicking on a button.
    """
    toast = Adw.Toast()
    toast.set_timeout(0)

    label = label or _("Loading...")

    adw_1_2 = Adw.get_major_version() > 1 or Adw.get_minor_version() > 1

    if adw_1_2:
        # this need libadwaita >=1.2
        box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=20)
        spinner = Gtk.Spinner.new()
        spinner.start()
        label = Gtk.Label(label=label)
        box.append(spinner)
        box.append(label)
        toast.set_custom_title(box)
    else:
        toast.set_title(label)

    toast.set_button_label(_("cancel"))

    cancellable.connect("done", lambda *_: toast.dismiss())
    cancellable.connect("error", lambda *_: toast.dismiss())
    if adw_1_2:
        # this need libadwaita 1.2
        toast.connect("button-clicked", lambda *_: cancellable.cancel())
    else:
        # for older adw, dismissing the toast will cancell the operation
        toast.connect("dismissed", lambda *_: cancellable.cancel())
    return toast
