# dialog_cache_outdated.py - inform the user to update the apt cache
#
#  Copyright (c) 2006 Canonical
#
#  Authors:
#       Sebastian Heinlein <sebastian.heinlein@web.de>
#
#  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 2 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, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA

import os
import gi
gi.require_version("Gdk", "4.0")
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("PackageKitGlib", "1.0")
from gi.repository import Gtk, Adw
from gi.repository import PackageKitGlib as packagekit
from gettext import gettext as _

from softwareproperties.gtk.utils import (
    setup_ui,
)


class ProgressDialog(Gtk.Window):
    """A small helper window to display progress"""

    def __init__(self, parent):
        Gtk.Window.__init__(self, title=_("Cache Refresh"))
        self.set_transient_for(parent)
        self.set_modal(True)
        self.set_deletable(False)

        self.box = Gtk.Box(spacing=6, orientation=Gtk.Orientation.VERTICAL)
        self.box.set_margin_top(12)
        self.box.set_margin_bottom(12)
        self.box.set_margin_start(12)
        self.box.set_margin_end(12)
        self.set_child(self.box)

        self.label = Gtk.Label(xalign=0)
        self.label.set_markup("<b><big>{}</big></b>".format(_("Refreshing software cache")))
        self.box.append(self.label)

        # create a progress bar
        self.progressbar = Gtk.ProgressBar()
        self.box.append(self.progressbar)


class DialogCacheOutdated:
    def __init__(self, parent, on_done, datadir):
        """setup up the gtk dialog"""
        self.parent = parent
        self.on_done = on_done

        setup_ui(self, os.path.join(datadir, "gtkbuilder", "dialog-cache-outofdate.ui"), domain="software-properties")
        self.dialog = self.dialog_cache_outofdate
        self.dialog.set_transient_for(parent)

    def _report_exception_and_finish(self, message, detail):
        d = Adw.MessageDialog.new(self.parent, str(message), str(detail))
        d.add_response("ok", _("_OK"))
        d.set_close_response("ok")
        d.connect("response", lambda d, r: (self.on_done() if callable(self.on_done) else None))
        d.present()

    def on_pktask_progress(self, progress, ptype, udata=(None,)):
        if ptype == packagekit.ProgressType.PERCENTAGE:
            perc = progress.get_property('percentage')
            self._pdia.progressbar.set_fraction(perc / 100.0)

    def on_pktask_finish(self, source, result, udata=(None,)):
        try:
            self._pktask.generic_finish(result)
        except Exception as e:
            self._pdia.hide()
            self.parent.set_sensitive(True)
            self._report_exception_and_finish(_("Error while refreshing cache"), str(e))
            return

        self._pdia.hide()
        self.parent.set_sensitive(True)
        if callable(self.on_done):
            self.on_done()

    def present(self):
        def _on_response(dialog, response_id):
            dialog.hide()
            if response_id == Gtk.ResponseType.APPLY:
                self._pktask = packagekit.Task()
                self._pdia = ProgressDialog(self.parent)
                self._pdia.present()
                self.parent.set_sensitive(False)
                try:
                    self._pktask.refresh_cache_async(
                        False,              # force
                        None,               # cancellable
                        self.on_pktask_progress,
                        (None,),            # progress data
                        self.on_pktask_finish,
                        (None,),            # finish data
                    )
                except Exception as e:
                    self._pdia.hide()
                    self.parent.set_sensitive(True)
                    self._report_exception_and_finish(_("Error while refreshing cache"), str(e))
            else:
                # User chose to close without reload; proceed to quit
                if callable(self.on_done):
                    self.on_done()

        self.dialog.set_modal(True)
        self.dialog.connect("response", _on_response)
        self.dialog.present()
