import xbmc
import xbmcgui
import xbmcvfs
import os
import xml.etree.ElementTree as ET
from xml.dom import minidom

# --- 新增的函数 ---

def get_record_file_path():
    """获取 skin_record.xml 文件的完整路径"""
    userdata_dir = xbmcvfs.translatePath('special://userdata/')
    skin_data_dir = os.path.join(userdata_dir, 'addon_data', 'skin.confluence.minsk')
    if not xbmcvfs.exists(skin_data_dir):
        xbmcvfs.mkdirs(skin_data_dir)
    return os.path.join(skin_data_dir, 'skin_record.xml')

def initialize_skin_record():
    """确保 skin_record.xml 文件存在并已正确初始化"""
    record_file = get_record_file_path()
    if not xbmcvfs.exists(record_file):
        root = ET.Element("skin_record")
        run_count_elem = ET.SubElement(root, "run_count")
        run_count_elem.text = "0"
        
        xml_str = minidom.parseString(ET.tostring(root)).toprettyxml(indent="  ")
        xml_str = '\n'.join([line for line in xml_str.split('\n') if line.strip()])
        
        try:
            with open(record_file, 'w', encoding='utf-8') as f:
                f.write(xml_str)
        except IOError as e:
            xbmc.log(f"创建记录文件失败: {e}", level=xbmc.LOGERROR)

def update_skin_record(new_count):
    """更新 skin_record.xml 文件中的 run_count 值"""
    record_file = get_record_file_path()
    initialize_skin_record()
    
    try:
        tree = ET.parse(record_file)
        root = tree.getroot()
        run_count_elem = root.find("run_count")
        if run_count_elem is None:
            run_count_elem = ET.SubElement(root, "run_count")
        run_count_elem.text = str(new_count)
        
        xml_str = minidom.parseString(ET.tostring(root)).toprettyxml(indent="  ")
        xml_str = '\n'.join([line for line in xml_str.split('\n') if line.strip()])
        
        with open(record_file, 'w', encoding='utf-8') as f:
            f.write(xml_str)
    except Exception as e:
        xbmc.log(f"更新 skin_record.xml 时出错: {e}", level=xbmc.LOGERROR)
        initialize_skin_record()

def get_run_count():
    """从 skin_record.xml 文件中获取当前的 run_count 值"""
    record_file = get_record_file_path()
    initialize_skin_record()
    
    try:
        tree = ET.parse(record_file)
        root = tree.getroot()
        run_count_elem = root.find("run_count")
        if run_count_elem is not None and run_count_elem.text.isdigit():
            return int(run_count_elem.text)
    except Exception as e:
        xbmc.log(f"读取 skin_record.xml 时出错: {e}", level=xbmc.LOGERROR)
    
    update_skin_record(0)
    return 0

# --- 原有的函数 ---

def open_skin_settings_and_navigate():
    """
    打开皮肤设置窗口，聚焦到指定控件，并模拟按下右键。
    """
    xbmc.executebuiltin('ActivateWindow(SkinSettings.xml,return)')
    xbmc.sleep(700)
    xbmc.executebuiltin('SetFocus(9000,0,true)')
    xbmc.sleep(100)
    xbmc.executebuiltin('Action(right)')

# --- 主逻辑 ---

xbmc.executebuiltin('Skin.SetString(skinnotice,1)')

initialize_skin_record()

if xbmc.getCondVisibility('Skin.HasSetting(skinnoticeoff)'):
    current_count = get_run_count()
    
    if current_count >= 30:  # 修改为大于等于30
        # 原有逻辑：处理 skinnoticeoff
        if xbmc.getCondVisibility('Skin.HasSetting(skinnoticeoff)'):
            xbmc.executebuiltin('Skin.ToggleSetting(skinnoticeoff)')
        
        # 新增逻辑：处理 discboxoffhome
        if xbmc.getCondVisibility('!Skin.HasSetting(discboxoffhome)'):
            xbmc.executebuiltin('Skin.ToggleSetting(discboxoffhome)')
        
        # 新增逻辑：处理 discboxoff（检查是否未设置）
        if xbmc.getCondVisibility('!Skin.HasSetting(discboxoff)'):
            xbmc.executebuiltin('Skin.ToggleSetting(discboxoff)')
        
        # 新增逻辑：处理 discboxoff500（检查是否未设置）
        if xbmc.getCondVisibility('!Skin.HasSetting(discboxoff500)'):
            xbmc.executebuiltin('Skin.ToggleSetting(discboxoff500)')
        
        # 重置计数
        update_skin_record(0)
    else:
        update_skin_record(current_count + 1)

else:
    dialog = xbmcgui.Dialog()
    heading = "功能未解锁"
    message = "该功能需要捐赠后升级皮肤解锁\n请访问CE交流QQ群(532568068)获取捐赠链接。\n可以通过皮肤设置长时间关闭该提示窗。"
    
    # 保持原始的按钮顺序
    yeslabel = "关闭"
    nolabel = "去设置"
    
    # 显示对话框
    response = dialog.yesno(heading, message, yeslabel, nolabel)

    # 根据用户选择执行操作
    if response == 1:
        open_skin_settings_and_navigate()
    else:
        # 两种情况都执行重置计数的操作
        update_skin_record(0)