
from gi.repository import GLib, GObject
import logging
from SystemUpdater.Core.dbus 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.SIGNAL_RUN_FIRST,
                                GObject.TYPE_NONE,
                                (   GObject.TYPE_INT,
                                )),
                    }
    
    def __init__(self, parent):
        GObject.GObject.__init__(self)
        self.dbus = get_bus()

    def run(self,trans=None):
        logging.info("Processing transaction")
        GLib.idle_add(self._run_transaction_idle,trans)

    def _run_transaction_idle(self,trans):
        """Run the transaction"""
        try:
            self._run_transaction(trans)
        except Exception as excep:
            logging.error(str(excep))
            trans.success = False

            tbk = traceback.format_exc()
            logging.error(str(tbk))
        else:
            trans.success = True

        return False

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

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

    def _run_transaction(self,trans):
        """This method needs to be implemented by the backends."""
        # 接入信号监听 备份的完成状态和信号 
        backup_proxy = self.dbus.get_object('com.kylin.backupserver','/')
        backup_proxy.connect_to_signal('sendBackupResult',self._backup_result_handler, dbus_interface="com.kylin.backup.server")                                          
        backup_proxy.connect_to_signal("sendRate",self._backup_rate_handler,dbus_interface="com.kylin.backup.server")

        # backup_name = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        backup_name = "test"
        logging.info("Start backup system before update, backup name: %s", backup_name)
        backup_interface = dbus.Interface(backup_proxy,dbus_interface='com.kylin.backup.server')
        backup_interface.autoBackUpForSystemUpdate_noreturn(backup_name, getpass.getuser(), os.getuid())
        logging.info("Backup process initiated.")
        # 备份过程通过信号监听进度和结果
        self.emit("backup-progress", 1)

