
from gi.repository import GLib, GObject
import logging
from SystemUpdater.Core.dbus_helper import get_bus
import getpass
import os
import traceback
import dbus

class BackUpBackend(GObject.GObject):
    __gsignals__ = {
        "transaction-done": (
            GObject.SignalFlags.RUN_FIRST,
            None,
            (GObject.TYPE_INT,)
        ),
        "backup-progress": (
            GObject.SignalFlags.RUN_FIRST,
            None,
            (GObject.TYPE_INT,)
        ),
    }

    def __init__(self, parent=None):
        super().__init__()
        self.dbus = get_bus()

    # -------------------- 公开接口 --------------------

    def run(self, trans=None):
        """Start running a backup transaction asynchronously."""
        logging.info("Processing backup transaction...")
        GLib.idle_add(self._run_transaction_idle, trans)

    # -------------------- 内部逻辑 --------------------

    def _run_transaction_idle(self, trans):
        """Run the transaction in an idle callback."""
        try:
            self._run_transaction(trans)
        except Exception:
            trans.backup_success = False
            logging.warning("Backup transaction failed...")
            self._backup_result_handler(False)

        return False  # 只运行一次

    def _run_transaction(self, trans):
        """Perform the actual backup via D-Bus."""
        backup_name = "system update backup for v11"

        # 获取 D-Bus 对象和接口
        proxy = self.dbus.get_object('com.kylin.systembackup', '/update')
        iface = dbus.Interface(proxy, dbus_interface='com.kylin.systembackup.manager')

        # 连接信号监听
        proxy.connect_to_signal(
            'sendAutoBackupResult',
            self._backup_result_handler,
            dbus_interface="com.kylin.systembackup.manager"
        )
        proxy.connect_to_signal(
            'sendRate',
            self._backup_rate_handler,
            dbus_interface="com.kylin.systembackup.manager"
        )

        logging.info("Starting system backup before update: %s", backup_name)
        iface.autoBackUpForSystemUpdate(backup_name, getpass.getuser(), os.getuid())

        # 初始进度通知
        self.emit("backup-progress", 1)
        logging.info("Backup process initiated and signal handlers registered.")

    # -------------------- 信号回调 --------------------

    def _backup_rate_handler(self, status, progress):
        """Handle backup progress updates from the backend."""
        self.emit("backup-progress", progress)

    def _backup_result_handler(self, result):
        """Handle backup completion result from the backend."""
        logging.info("Backup result: %s", result)
        self.emit("transaction-done", result)