import { _decorator, sys } from 'cc';
import { Constants } from './Constants';
import { Utils } from '../utils/Utils';
import { Singleton } from '../core/manager/Singleton';
import { audioMgr } from '../core/manager/AudioManager';
import MsgHints from '../utils/MsgHints';
const { ccclass, property } = _decorator;

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

    public get data() {
        if (!this._data) {
            this.loadFromCache();
            //使用Proxy代理data对象 拦截属性修改
            this._data = new Proxy(this._data, {
                set: (target, prop, value) => {
                    target[prop] = value;
                    this.saveToCache();
                    if (prop === "bgMusic") {//如果是bgMusic 变化 自动处理音乐逻辑
                        MsgHints.show(value? `bg music has been turned on`:`bg music has been turned off`);
                        if(value) {
                            audioMgr.play(Constants.audios.BGM, true);
                        } else {
                            audioMgr.stop(Constants.audios.BGM);
                        }
                    }else if(prop === "soundFx") {//如果是bgMusic 变化
                        MsgHints.show(value?`sound has been turned on`:`sound has been turned off`);
                    }else if(prop === "vibrate") {//如果是vibration 变化
                        MsgHints.show(value?`vibrate has been turned on`:`vibrate has been turned off`);
                    }
                    return true;
                }
            });
        }
        return this._data;
    }

    /**
     * 读取数据缓存
     */
    public loadFromCache(){
        let l = sys.localStorage.getItem(Constants.localCache.settingData);
        if(l){
            this._data = JSON.parse(Utils.decrypt(l));
        }else{
            //没有数据保存一份默认的初始数据
            this._data = {
                bgMusic: true,//背景音乐开关
                soundFx: true,//音效开关
                vibrate: false,//震动开关
                sensitivity: 0.5 //相机旋转的灵敏度 值越大移动越快 灵敏度越高
            }
            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(Constants.localCache.settingData, Utils.encrypt(data));
    }

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