/**
 * @class
 * unotify
 */
import uloop from './uloop';

//获取cid: http://116.62.143.3:10080/iot-project-js/doorlock/issues/4

class unotify{
	//在一个周期内获取cid
	static  getCid(successCallback, errorCallback){
		this.UpdateCid((response) => {
			successCallback(response);
		}, (error) => {
			errorCallback(error);
		});
	}
	//周期性获取cid,周期可调整
	static getCidPeriotic(times){
		var self = this;
		return new Promise(function(resolve, reject){
			new uloop({
				loopContent: () => {
					return self.getCidOnce();
				},
				times: times,
				interval:{
					delay: 1000,
					cb: {
						success: (response) => {
							console.log('intervalcbSuccess:'+JSON.stringify(response));	
						},
						error: (error) => {
							console.log('intervalcbError:'+JSON.stringify(error));
						}
					}
				}, 
				fincb: {
					success: (response) => {
						console.log('fincbSuccess:'+JSON.stringify(response));	
						resolve(response);
					},
					error: (error) => {
				    	console.log('fincbSuccess:'+JSON.stringify(error));
				    	if(error == 'timeout'){
				    		resolve(null);
				    	}
					},
					complete: () => {}
				},
				stopcondition: async (response) => {
					if(response != null && response != 'null' ){
						return true;
					}
				}
			}).start();
		});
	}
	//单次获取cid
	static getCidOnce(){
		var clientInfo = plus.push.getClientInfo();
		if(clientInfo && clientInfo.hasOwnProperty('clientid') && clientInfo.clientid){
			return(clientInfo.clientid);
		}else{
			return(null);
		}
	}
	//长期不断循环获取cid,并更新cid
	static async UpdateCid(successCallback, errorCallback){
		var cid = null;
		var oldCid = null;
		try{
			cid = await this.getCidPeriotic(9);
			if(cid != null && cid != oldCid){
				iot.business.api.send('user/updateCid',{
					data: {
						clienId: cid
					},
					success: (response) => {
						console.log(response);
						if(typeof successCallback == 'function'){
							successCallback('cid updateSuccess');
						}
					},
					error: (error) => {
						console.log(error);
						errorCallback(error);
					}
				}, true, false);
			}else{
				successCallback('cid not updated');
			}
		}
		catch (err){
			console.log(err);
			if(typeof errorCallback == 'function'){
				errorCallback(err);
			}
		}
	}
}
export default unotify;