import { _decorator, sys } from 'cc';
import { Singleton } from '../core/manager/Singleton';
import Utils from '../core/utils/Utils';
import { GameConst } from '../core/common/GameConst';
const { ccclass, property } = _decorator;

@ccclass("SettingData")
class SettingData extends Singleton{
    private _data: any = null;

    public get data() {
        if (!this._data) {
            this.loadFromCache();
        }
        return this._data;
    }

    /**
     * 读取数据缓存
     */
    public loadFromCache(){
        let l = sys.localStorage.getItem(GameConst.localCache.settingData);
        if(l){
            this._data = JSON.parse(Utils.decrypt(l));
        }else{
            //没有数据保存一份默认的初始数据
            this._data = {
                bgMusic: true,//背景音乐开关
                soundFx: true,//音效开关
                vibration: false//震动开关
            }
            this.saveToCache();
        }
        return this.data;
    }

    /**
    * 得到设置的数据数组
    */
    public getSettingDatas() {
        const displayNames = ["背景音乐", "音效", "震动"];
        const dataKeys = Object.keys(this.data);
        // 确保字段顺序一致
        return dataKeys.map((key, index) => ({
            name: displayNames[index],
            selected: this.data[key]
        }));
    }

    /**
     * 保存到缓存中
     */
    public saveToCache(){
        const data = JSON.stringify(this.data);
        //序列化JSON字符串过后加密存储
        sys.localStorage.setItem(GameConst.localCache.settingData, Utils.encrypt(data));
    }

    /**
     * 删除缓存
     */
    public remove(){
        sys.localStorage.removeItem(GameConst.localCache.settingData);
        this.loadFromCache();
    }
}
//全局单例
export const settingData = SettingData.ins();