import os
import shlex
from common.utils import HostMessage, PathManager
from pathlib import Path
def check_whitelist(func):
    def wrapper(self, *args, **kwargs):
        if self.conf is None:
            return  
        return func(self, *args, **kwargs)
    return wrapper

class WhiteList(HostMessage, PathManager):

    def __init__(self, package,container_name=None):

        self.package = package
        self.container_name = container_name
        try:
            self.white= self.get_config_json(self.WHITELIST_FILE)
        except Exception:
            self.white = {}

        self.conf = self.white.get(self.package, None)
        # self.update_services
    
    @check_whitelist
    def update_services(self):
        services = self.conf.get("services", None)
        if services is None:
            return
        for service in services:
            self.run_command(f"systemctl restart {service}")
    
    @check_whitelist
    def remove_files(self):
        files = self.conf.get("remove_files", None)
        if files is None:
            return
        
        for file_path in files:
            try:
                sanitized_path = shlex.quote(file_path)
                self.run_command(f"rm -rf {sanitized_path}")
            except Exception as e:
                print(f"删除文件 {file_path} 失败: {e}")

    @check_whitelist
    def update_usr_desktops(self, unpack_path):
        desktops = self.conf.get("desktops", None)
        if desktops is None:
            return
        for desktop in desktops:
            self.copy_file(unpack_path + desktop, unpack_path +"/usr/share/applications/")

    @check_whitelist
    def update_bin_files(self):
        command = self.conf.get("command", None)
        if command is None:
            return
        
        for cmd in command:
            file_path = "/opt/kare/usr/bin/{}".format(cmd)
            content = '#!/bin/bash\nkare run {} {} "$@"\n'.format(self.package,cmd)

            try:
                os.makedirs(os.path.dirname(file_path), exist_ok=True)
                with open(file_path, 'w') as file:
                    file.write(content)
                self.run_command("chmod +x {}".format(file_path))
            except Exception as e:
                print("创建bin文件 {} 失败: {}".format(file_path, e))
    @check_whitelist
    def create_symbol_link(self):
        source_dir_lists = self.conf.get("symbol_link",None)
        if source_dir_lists is None:
            return
        for source_dir in source_dir_lists:
            target_dir = f'{self.PACKAGE_SAVE_PATH}{self.container_name}/merge{source_dir}'
            if not Path(source_dir).parent.exists():
                Path(source_dir).parent.mkdir(parents=True, exist_ok=True)
            try:
                Path(source_dir).symlink_to(Path(target_dir), target_is_directory=True)
            except FileExistsError:
                print(f"错误：{source_dir} 已经存在。")
            except OSError as e:
                print(f"无法创建软链接：{e}")

            
            

