import configparser
import subprocess
import dbus
import dbus.service
from common.container import Container
from common.errors import KareErrors as RError
from common.log import Log
from common.utils import RequireRoot, GlobalSingleton
from common.package import Package
import os
from common.whitelist import WhiteList

@RequireRoot
class Remove(RError, Container, GlobalSingleton, Package):

    LOCK_FILE = "/var/lock/kare-remove.lock"
    flag = False

    def __init__(self, packages):
        GlobalSingleton.__init__(self)
        self.packages = packages
        self.log = Log("/var/log/kare/kare-install.log")
        Container.__init__(self, log=self.log)
        self.upgrade = False
        for package in self.packages:
            if self.is_package_installed(package) is False:
                continue
            self._check_remove(package)
            self._purge_package(package)
            self._remove_package(package)
            self._update_bio_config(package)
            self._update_config(package)
    
    def is_package_installed(self, package):
        data = self.get_config_json(self.INSTALL_JSON, package)
        if data is None:
            self.log.warning(f"应用包: {package}未安装")
            print(f"应用包: {package}未安装 ")
            return False
        return True


    def _purge_package(self, package):
        # 挂载overlay
        conf = self.get_config_json(self.INSTALL_JSON, package)
        package_path = conf.get("path")
        release_path = self.get_release_path(conf.get("base_env"))
        self.upgrade = conf.get("upgrade", False)
        if self.upgrade:
            self.clean_package(package_path, conf.get("driver", False), self.upgrade, conf.get("dkms", False))
            return
        base_dirs = self.get_base_dirs(release_path)
        self.mount_overlay(base_dirs, package_path)

        # 构建卸载命令
        cmd = "SYSTEMCTL_FORCE_BUS=1 SYSTEMD_IGNORE_CHROOT=1 dpkg --purge --force-all {}".format(package)
        self.container.start_container()
        exec = self.container.exec(package_path + "/merge", cmd)
        self.run_command_realtime(exec, self.log)

        self.clean_package(package_path, conf.get("driver", False), self.upgrade, conf.get("dkms", False))

    def _remove_package(self, package):
        self.remove_package(package)
        self._remove_desktop_files(package)
        WhiteList(package).remove_files()

    def _remove_desktop_files(self, package):
        conf = self.get_config_json(self.INSTALL_JSON, package)
        desktop_files = conf.get("desktop_files", None)
        if desktop_files is None:
            return
        self.log.info(f"desktop files: {desktop_files}")
        _, user = self.get_user_by_login1
        for desktop in desktop_files:
            desktop=desktop.split("/")[-1]
            if os.path.exists(f"/home/{user}/桌面/") is False:
                return
            if desktop in os.listdir(f"/home/{user}/桌面/"):
                self.log.info(f"删除桌面文件: {desktop}")
                os.remove(f"/home/{user}/桌面/{desktop}")

    def _update_config(self, package):
        self.set_config_json(self.INSTALL_JSON, package)

    def _check_remove(self, package):
        try:
            bus = dbus.SystemBus()
            proxy = bus.get_object(
                "com.kylin.kysdk.applicationsec",
                "/com/kylin/kysdk/applicationsec"
            )
            interface = dbus.Interface(
                proxy,
                dbus_interface="com.kylin.kysdk.applicationsec.antiuninstall"
            )
            result = interface.GetPackageUninstallStatus(package)
        except Exception as e:
            # TODO 异常处理(当前方案按照调用不到dbus默认允许卸载)
            self.log.error(f"获取安全卸载状态 DBus 调用失败: {e}")
            return True

        if result == 0:
            return True
        else:
            raise RuntimeError(self.KYSEC_REJECT_REMOVE)

    def _update_bio_config(self, package):
        try:
            conf = self.get_config_json(self.INSTALL_JSON, package)
            driver_name = conf.get("bio_driver_name")
            print("finish get bio driver name")
            bio_config_path = "/etc/biometric-auth/biometric-drivers.conf"
            config = configparser.ConfigParser()
            config.optionxform = str
            config.read(bio_config_path)
            if driver_name in config:
                config.remove_section(driver_name)
                with open(bio_config_path, "w") as f:
                    config.write(f)
                print(f"已删除生物识别配置项: {driver_name}")
                
                files=conf.get("file")
                print(f"extra_file:{files}")
                extra_file=files[0]
                if "extra" in extra_file:
                    parts = extra_file.split('/')
                    if "drivers" in parts and "extra" in parts:
                        # 找到 extra 后面的部分，例如 eyecool-finger
                        drivers_extra_index = parts.index("extra") + 1
                        if len(parts) > drivers_extra_index:
                            extra_dir_one = parts[drivers_extra_index]

                    command = f"sudo rm -rf /opt/biometric/drivers/extra/{extra_dir_one}/"
                    print(f"command:{command}")
                    result = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
                    if result.returncode:
                        error_msg = result.stderr.strip()
                        if error_msg:
                            print(f"Error executing command: {command}")
                            print(f"Error details: {error_msg}")
            else:
                print(f"未找到生物识别配置项: {driver_name}")

        except Exception as e:
            self.log.error(f"更新生物识别配置文件失败: {e}")
    