class Update{
	constructor(curV,newV,url) {//当前版本号、最新版本号以及获取最新安装包地址
	    this.curV = curV;
	    this.newV = newV;
	    this.url = url;
	}
	
	startUpdate(){
		if(this.curV != this.newV){
			console.log("需要更新...");
			this.downWgt();
		}else{
			console.log("不需要更新");
			this.onNoNeedUpdate();
			return ; 
		}
	}
	
	onStateChanged(download, status) {
//		console.log((download.downloadedSize/download.totalSize).toFixed(2)*100)
	}

	downWgt(){
		this.onDownloadStart();
		var dtask = plus.downloader.createDownload( this.url, {}, (d,status)=>{
			if ( status == 200 ) { 
				this.onDownloadSuccess();
				console.log("下载wgt成功："+d.filename);
				this.installWgt(d.filename);	// 安装wgt包
			} else {
				console.log("下载wgt失败！");
				this.onError(status);
			}
		});
		dtask.addEventListener( "statechanged", this.onStateChanged, false );
		dtask.start();
	}

	installWgt(path){
		this.onInstallStart();
		plus.runtime.install(path,{force: true},()=>{ //强制安装 不进行版本校验
			console.log("安装wgt文件成功！");
			this.onInstallSuccess();
			plus.runtime.restart();
		},(e)=>{
			this.onError(e);
			console.log("安装wgt文件失败["+e.code+"]："+e.message);
		});
	}

	onDownloadStart(){
		console.log(`download wgt file start`);
	}

	onDownloadSuccess(){
    	console.log(`download wgt file success`);
    }

    onError(){
    	console.log(`operate onError`);
    }

    onInstallStart(){
    	console.log(`install wgt file start`);
    }

    onInstallSuccess(){
    	console.log(`install wgt file success`);
    }
    
    onNoNeedUpdate(){
    	console.log(`no need update`);
    }
}

export default Update;