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

@ccclass("LevelsData")
export class LevelsData 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.levelsData);
        if(l){
            this._data = JSON.parse(Utils.decrypt(l));
        }else{
            //没有数据保存一份默认的初始数据
            this._data = {
            }
            this.saveToCache();
        }
        return this.data;
    }
    
    /**
     * 得到模型名字数组
     */
    public getModesNames():Array<any>{
        let modelNames = csvMgr.getTableArr("model_names")
        return modelNames.map(item => item.name);
    }

    /**
     * 得到当前关卡下的数据
     */
    public getCurLevelInfo(){
        let levels = csvMgr.getTableArr("levels");
        let lv = Data.user.lv - 1;
        if(lv >= levels.length){
            return levels[levels.length -1];
        }else{
            return levels[lv];
        }
    }

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

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