import { _decorator, Prefab, sys } from "cc";
import { constants } from "./constants";
import { utils } from "./utils";
import { localConfig } from "../manager/localConfig";
import Data from "../scripts/core/manager/Data";
import Utils from "../scripts/core/utils/Utils";

const { ccclass, property } = _decorator;

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

    //关卡数据
    public _levelTable: Array<any> = null;
    public get levelTable(){
        if(!this._levelTable){
            this._levelTable = localConfig.instance.getTableArr('levels');
        }
        return this._levelTable;
    }
    
    public _modelsTable: Array<any> = null;
    public get modelsTable(){
        if(!this._modelsTable){
            this._modelsTable = localConfig.instance.getTableArr('model_names');
        }
        return this._modelsTable;
    }

    /**单例*/
    public static ins() {
        if (!this.instance) {
            this.instance = new levelsData();
        }
        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 = {};
            this.saveToCache();
        }
    }

    /**
     * 得到解锁的模型名字数组
     */
    public getDeblockDatas():Array<any>{
        return this.modelsTable.map(item => item.name);
    }

    /**
     * 得到标准模型名字数组
     */
    public getNormModelDatas():Array<any>{
        return this.modelsTable.map(item => item.name);
    }


    /**
     * 得到当前关卡下的数据
     */
    public getCurLevelInfo(){
        let datas:Array<any> = this.levelTable;
        let lv = Data.user.lv - 1;
        if(lv > datas.length){
            return datas[datas.length -1];
        }else{
            return datas[lv];
        }
    }

    public async LoadItemPrefabByName(name: string) {
        if(utils.isNull(name))return null;
        return Utils.loadRes(name, "item_bundle", Prefab);
    }

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

    /**
     * 删除缓存
     */
    public remove(){
        sys.localStorage.removeItem(constants.localCache.levelsData);
        this.loadFromCache();
    }
}
export default levelsData.ins();