import logging
from gi.repository import PackageKitGlib

class PackageKit:
  def __init__(self):
    self.client = PackageKitGlib.Client.new()

  def refresh_cache(self, progress_callback, finished_callback, error_callback = None):
    self.client.refresh_cache_async(True, None, progress_callback, (), self._task_finished, finished_callback, error_callback)

  def _task_finished(self, client, result, finished_callback, error_callback):
    try:
      finished_callback(client.generic_finish(result))
    except:
      logging.exception("PackageKit task failed")
      if error_callback:
        error_callback(result)

  def get_available_updates(self):
    results = self.client.get_updates(1 << PackageKitGlib.FilterEnum.NONE, None, lambda *_: None, (), None)
    return results.get_package_sack()

  def download_updates(self, progress_callback, finished_callback, error_callback = None):
    sack = self.get_available_updates()
    sack.remove_by_filter(lambda package: package.get_info() not in (PackageKitGlib.InfoEnum.OBSOLETING, PackageKitGlib.InfoEnum.REMOVING))
    package_ids = sack.get_ids()
    self.client.update_packages_async(1 << PackageKitGlib.TransactionFlagEnum.ONLY_DOWNLOAD, package_ids, None, progress_callback, (), self._task_finished, finished_callback, error_callback)

  def trigger_offline_upgrade(self):
    try:
      PackageKitGlib.offline_trigger(PackageKitGlib.OfflineAction.REBOOT, None)
      return True
    except:
      logging.exception("Error on triggering offline upgrade")
      return False

