# widgets/loaderpage.py
#
# Copyright 2020-2023 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 typing import Optional

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

from ..fetcher import Fetcher


@Gtk.Template(resource_path="/net/kirgroup/confy/widgets/loaderpage.ui")
class LoaderPage(Adw.Bin):
    __gtype_name__ = "ConfyLoaderPage"

    progressbar = Gtk.Template.Child()  # type: ignore
    cancel_button = Gtk.Template.Child()  # type: ignore

    fetcher: Optional[Fetcher] = None

    def __init__(self):
        super().__init__()
        GLib.timeout_add(200, self._do_pulse)

    @Gtk.Template.Callback()
    def on_cancel_button_clicked(self, *_):
        if self.fetcher:
            self.fetcher.cancel()

    def set_fetcher(self, fetcher):
        self.fetcher = fetcher
        self.progressbar.set_fraction(0)
        fetcher.bind_property("fraction", self.progressbar, "fraction")

    def _do_pulse(self, *args):
        if self.progressbar.get_fraction() > 0:
            return False
        self.progressbar.pulse()
        return True
