/**
 * @class
 * loop
 */
 
//轮询通用方法：http://116.62.143.3:10080/iot-project-js/doorlock/issues/1

class Loop{
	constructor(params) {
       	this.handle = null;
		this.watcher = null;
		this.time = null;
		this.loopContent = params.loopContent;
		this.times = params.times || 10;
		this.fincb = params.fincb;
		this.intervalTime = params.interval.delay;
		this.intervalcb = params.interval.cb;
		this.stopcondition = params.stopcondition;
		this.canSend = true;
		this.canDo = true;
		this.i = 0;
    }

	clearTime(){
		clearInterval(this.handle);
		clearInterval(this.watcher);
		clearTimeout(this.time);
	}
	
	async sendRequest(){
		this.canSend = false;
		try{
			var response = null;
			response = await this.loopContent();
			console.log(response);
			if(await this.stopcondition(response)){
				if(this.fincb!= null){
					this.fincb.success(response);
					this.fincb.complete();
				}
				this.clearTime();
				this.canSend = false;
			}else{
				if(this.intervalcb!= null){
					this.intervalcb.success(response);
				}
				this.canSend = true;
			}
		}
		catch (error){
			if(this.intervalcb!= null){
				if(this.intervalcb.error(error)){
					this.canSend = true;
				}else{
					if(this.fincb!= null){   
						this.fincb.error(error);
						this.fincb.complete();
						this.clearTime();
					}
				}		
			}
		}
	}

	start(){
		console.log("开始");
		console.log("第"+this.i+"次发送了请求");
		console.log("发送时间"+new Date().getTime());
		this.i++;
		this.sendRequest();
		this.watcher = setInterval(() => {
			if(this.canSend && this.canDo){
				this.canDo = false;
				console.log("第"+this.i+"次发送了请求");
				console.log("发送时间"+new Date().getTime());
				this.i++;
				this.sendRequest();
			}
		},1000);
		
		let times = 1;
		this.handle = setInterval(() => {
			times++;
			console.log('times'+times);
			if(times > this.times){
				this.clearTime();
				this.canDo = false;
				this.fincb.error('timeout');
				this.fincb.complete();
				this.intervalcb = null;
				this.fincb = null;
			}else{
				this.canDo = true;
			}
		},this.intervalTime);
	}
}
export default Loop;
