import preferences from "@ohos:data.preferences";
import type common from "@ohos:app.ability.common";
class ThemeManager {
    private static preference: preferences.Preferences | null = null;
    private static listeners: Map<string, (isDark: boolean) => void> = new Map();
    private static isSettingTheme: boolean = false;
    private static currentTheme: boolean = false;
    private static isInitialized: boolean = false;
    private static initializationPromise: Promise<void> | null = null;
    // 关键修复：使用官方推荐的初始化模式 [1,4](@ref)
    static async initTheme(context: common.UIAbilityContext): Promise<void> {
        if (ThemeManager.initializationPromise) {
            return ThemeManager.initializationPromise;
        }
        ThemeManager.initializationPromise = (async () => {
            try {
                if (ThemeManager.isInitialized) {
                    return;
                }
                ThemeManager.preference = await preferences.getPreferences(context, 'theme_settings');
                // 关键修复：确保主题设置存在并正确初始化 [1](@ref)
                const hasTheme = await ThemeManager.preference.has('globalDarkMode');
                if (!hasTheme) {
                    await ThemeManager.preference.put('globalDarkMode', false);
                    await ThemeManager.preference.flush();
                    console.info('初始化默认主题设置: globalDarkMode = false');
                }
                // 关键修复：直接读取并同步状态 [4](@ref)
                const savedTheme = await ThemeManager.preference.get('globalDarkMode', false);
                ThemeManager.currentTheme = Boolean(savedTheme);
                ThemeManager.isInitialized = true;
                console.info(`主题管理器初始化完成: ${ThemeManager.currentTheme ? '深色' : '浅色'}`);
            }
            catch (error) {
                console.error('主题初始化失败: ' + JSON.stringify(error));
                ThemeManager.currentTheme = false;
                ThemeManager.isInitialized = true;
            }
        })();
        return ThemeManager.initializationPromise;
    }
    // 关键修复：原子化主题设置操作 [1,4](@ref)
    static async setTheme(isDark: boolean): Promise<void> {
        if (ThemeManager.isSettingTheme ||
            !ThemeManager.isInitialized ||
            !ThemeManager.preference ||
            ThemeManager.currentTheme === isDark) {
            return;
        }
        ThemeManager.isSettingTheme = true;
        try {
            // 1. 先更新持久化存储（确保数据安全）
            await ThemeManager.preference.put('globalDarkMode', isDark);
            await ThemeManager.preference.flush();
            // 2. 再更新内存状态
            ThemeManager.currentTheme = isDark;
            console.info(`主题设置成功: ${isDark ? '深色' : '浅色'}`);
            // 3. 最后通知监听器（延迟确保状态一致性）
            setTimeout(() => {
                ThemeManager.notifyListeners(isDark);
            }, 50);
        }
        catch (error) {
            console.error('设置主题失败: ' + JSON.stringify(error));
            // 失败时保持原有状态
        }
        finally {
            ThemeManager.isSettingTheme = false;
        }
    }
    // 关键修复：优化状态获取逻辑 [4](@ref)
    static async getIsDarkMode(): Promise<boolean> {
        if (!ThemeManager.isInitialized) {
            return false;
        }
        if (ThemeManager.preference) {
            try {
                // 双重验证：确保内存与持久化状态一致
                const savedTheme = await ThemeManager.preference.get('globalDarkMode', ThemeManager.currentTheme);
                const persistentTheme = Boolean(savedTheme);
                if (ThemeManager.currentTheme !== persistentTheme) {
                    console.warn(`主题状态不一致，正在同步: 内存=${ThemeManager.currentTheme}, 持久化=${persistentTheme}`);
                    ThemeManager.currentTheme = persistentTheme;
                }
            }
            catch (error) {
                console.error('获取持久化状态失败，使用缓存: ' + JSON.stringify(error));
            }
        }
        return ThemeManager.currentTheme;
    }
    // 关键新增：同步状态验证方法 [4](@ref)
    static getCurrentThemeSync(): boolean {
        return ThemeManager.currentTheme;
    }
    // 关键新增：强制状态同步 [4](@ref)
    static async forceSync(): Promise<boolean> {
        if (!ThemeManager.isInitialized || !ThemeManager.preference) {
            return false;
        }
        try {
            const savedTheme = await ThemeManager.preference.get('globalDarkMode', ThemeManager.currentTheme);
            const newTheme = Boolean(savedTheme);
            if (ThemeManager.currentTheme !== newTheme) {
                ThemeManager.currentTheme = newTheme;
                ThemeManager.notifyListeners(newTheme);
                console.info(`强制同步完成: ${newTheme ? '深色' : '浅色'}`);
            }
            return true;
        }
        catch (error) {
            console.error('强制同步失败: ' + JSON.stringify(error));
            return false;
        }
    }
    // 监听器管理（保持不变）
    static addListener(callback: (isDark: boolean) => void): string {
        const id = Math.random().toString(36).substring(2, 9);
        ThemeManager.listeners.set(id, callback);
        return id;
    }
    static removeListener(id: string): void {
        ThemeManager.listeners.delete(id);
    }
    static hasListener(callback: (isDark: boolean) => void): boolean {
        for (const listener of ThemeManager.listeners.values()) {
            if (listener === callback) {
                return true;
            }
        }
        return false;
    }
    private static notifyListeners(isDark: boolean): void {
        ThemeManager.listeners.forEach((callback, id) => {
            try {
                setTimeout(() => {
                    callback(isDark);
                }, 0);
            }
            catch (error) {
                console.error(`监听器 ${id} 执行错误: ${JSON.stringify(error)}`);
            }
        });
    }
}
export default ThemeManager;
