class Update{
	constructor(url,needRestart) {//当前版本号、最新版本号以及获取最新安装包地址
	    this.url = url;
	    this.needRestart = false || needRestart;
	    this.filename = '';
	}
	
	onStateChanged(download, status) {
//		console.log((download.downloadedSize/download.totalSize).toFixed(2)*100)
	}

	downWgt(){
		this.onDownloadStart();
		var dtask = plus.downloader.createDownload( this.url, {retry: 0}, (d,status)=>{
			console.log(status);
			if ( status == 200 ) { 
				this.onDownloadSuccess();
				console.log("下载wgt成功："+d.filename);
				this.filename = 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.io.resolveLocalFileSystemURL(this.filename, function(entity) {
                entity.remove();
                console.log("删除wgt文件成功")
            }, function(error) {
                console.log(error);
            });
			//判断是否需要重启
			if(this.needRestart){
				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`);
    }
}

export default Update;