import { _decorator, Component, Node, sys } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SubPackageLoader')
export class SubPackageLoader {
    
    static load(packages:string[],progressCallBack:Function,completeCallBack:Function,errorCallback?:Function):void{
        console.log("平台："+sys.browserType);
        // switch (sys.browserType) {
            // case sys.BROWSER_TYPE_WECHAT:
                this.__loadWX(packages,progressCallBack,completeCallBack,errorCallback);
        //         break;
        
        //     default:
        //         break;
        // }
    }

    /**
     * 微信
     * @param packages 
     * @param progressCallBack 
     * @param completeCallBack 
     */
    private static __loadWX(packages:string[],progressCallBack:Function,completeCallBack:Function,errorCallback?:Function):void{
        console.log("wx subpackage load");
        let wx:any=window["wx"];
        let packageName:string;
        let loadIndex:number=0;
        let total:number=packages.length;
        let loadTask:any;
        for (let index = 0; index < packages.length; index++) {
            packageName = packages[index];
            loadTask=wx.loadSubpackage({
                name:packageName,
                success:(res)=>{
                    loadIndex++;
                    if(loadIndex>=total){
                        if(completeCallBack){
                            completeCallBack();
                        }
                    }
                },
                fail:(err)=>{
                    console.error(err);
                    if(errorCallback){
                        errorCallback(packageName+"加载出错!");
                    }
                }
            })
            loadTask.onProgressUpdate(res=>{
                if(progressCallBack){
                    progressCallBack(loadIndex+res.progress);
                }
            })
        }
    }
}
