import { _decorator, sys } from "cc";
import { constants } from "./constants";
import { utils } from "./utils";
const { ccclass, property } = _decorator;

@ccclass("settingData")
export class settingData {
    public static instance: settingData = null;
    public data: any = null;

    /**单例*/
    public static ins() {
        if (!this.instance) {
            this.instance = new settingData();
        }
        return this.instance;
    }

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

    /*修改音效状态
     */
    public changeStatus(idx: number){
        if(idx == 0){
            this.data.bg_music_status = !this.data.bg_music_status;
        }else if(idx == 1){
            this.data.sound_status = !this.data.sound_status;
        }else if(idx == 2){
            this.data.shock_status = !this.data.shock_status;
        }
        this.saveToCache();
    }

    /**
     * 得到设置的数据数组
     */
    public getSettingDatas():Array<any>{
        let datas:Array<any> = [
            {name: "背景音乐",
             selected: this.data.bg_music_status
            },
            {name: "音效",
             selected: this.data.sound_status
            },
            {name: "震动",
             selected: this.data.sound_status
            }
        ];
        return datas;
    }

    /**
     * 保存到缓存中
     */
    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 default settingData.ins();