
import { _decorator, Node, resources,instantiate,error,find,Prefab,  SpriteFrame, sys } from 'cc';
import { encryptjs }  from "./encryptjs/encryptjs"
const { ccclass, property } = _decorator;


@ccclass('LoadConfig')
export class LoadConfig {

    /**
     * @method dataRead 读取游戏加密数据，返回解密之后的文本
     */
     public static dataRead(key:string):any{
        var str = sys.localStorage.getItem(key);
        if(str == null)
            return '';
        //console.log('Read:'+str)
        var text1=encryptjs.decrypt(str,"encryptdata*321",256);//得到解密之后的文本
        var text2=encryptjs.decrypt(text1,"encryptdata*123",128);//得到解密之后的文本
        //console.log('Readencryptjs:'+JSON.parse(text2))
        return JSON.parse(text2);
    } 
    
    /**
     * @method dataWrite 保存加密游戏数据
     */
     public static dataWrite(key:string,val:any){
        //console.log('write:'+val)
        var str = JSON.stringify(val);
        if(str.length == 0)
            return;
        var text1 = encryptjs.encrypt(str,"encryptdata*123",128);
        var text2 = encryptjs.encrypt(text1,"encryptdata*321",256);
        //console.log('writeencryptjs:'+text2)
        sys.localStorage.setItem(key, text2);
    }

    /**
     * @method dataWrite 移除保存的游戏数据
     */
     public static dataRemove(key:string){
        sys.localStorage.removeItem(key)
    }


    /**
     * 加载资源
     * @param url   资源路径
     * @param cb    回调
     * @method loadRes
     */
    private static loadRes (url: string, cb: Function = ()=>{}) {
        console.log(url);
        resources.load(url,(err: any, res: any)=>{
            if (err) {
                error(err.message || err);
                cb(err, res);
                return;
            }

            cb && cb(null, res);
        })
    }

    /**
     * 获取动态资源
     * @param SpritePath 路径 
     * @param cb 回调函数
     */
    public static getResource (SpritePath: string,cb?: Function) {
        this.loadRes(SpritePath,cb);
    }

    /**
     * 加载data文件所有用户数据
     */
    public static loadData(name:string,cb: Function){
        resources.loadDir('datas/data',(err:any,object:any)=>{
            if(err){
                return;
            }
            cb(object[object.length-1].json[name]);
        })
    }

    /**
     * 创建ui界面
     * @param path ui路径
     * @param cb 回调函数
     * @param parent 父节点
     */
    public static createUI (path: string, cb?: Function, parent?: Node) {
         this.getResource(path, function (err: {}, prefab: Prefab) {
            if (err) return;
            let node: Node = instantiate(prefab);
            
            if (!parent) {
                parent = find("Canvas") as Node;
            }
            parent.addChild(node);
            node.setPosition(0, 0, 0);
            cb && cb(null, node);
        });
     }

     

}
