class Subscriber {
	constructor(o){
		this.sock = null;
		var opt = {
			debug: true,
			onmessage: function(o) {
					
			}
		}		
		this.opt = jQuery.extend(opt, o);
		console.log(this.opt.id);
		var me = this;
		this.id = o.id;
		
		this.connect();
		var n = 0;
		this.timerhandle = setInterval(function(){
			if (me.sock == null || me.sock.readyState == WebSocket.CLOSED) {
				me.connect();
			}
			n++;
			if (n % 1 == 0 && me.sock && me.sock.readyState == WebSocket.OPEN) { //60초에 한번씩 ping
				me._send({cmd: 'ping'});
			}
		//}, 1000*15); //ping 체크 15 초마다
		}, 1000*60); //ping 1분마다로 변경
	}
	_send(args){ // 주 역할이 아니기 때문에 _ 를 붙인다
		if (!this.sock || this.sock.readyState != WebSocket.OPEN) {
			console.log('ws closed. data is not sent :' + JSON.stringify(args));
			return;
		}
		if (typeof(args) == 'object') {
			args = JSON.stringify(args);
		}
		if (this.opt.debug)
			console.log('sending : '+args);
		this.sock.send(args);
	}
	onopen(){
		var me = this;
		this._send({
			cmd: 'subscribe',
			groupid: me.opt.groupid,
			id: me.opt.id,
		});
	}
	onclose(){
		console.log('connection closed');
		this.sock = null;
	}
	onmessage(o) 
	{
		if (this.opt.debug)
			console.log(o.data);
		this.opt.onmessage(o.data);
	}
	connect(){
		var me = this;
		try {
			var sock = new WebSocket("ws://l07.moddev.kr:2188/");
			console.log('new web socket' + sock);
			sock.onmessage = function(o){  // ws.onmessage = this.onmessage 할 경우는 onmessage 내에서 컨텍스트가 달라진다
				me.onmessage(o);
			};				
			sock.onopen = function(){
				me.onopen();
			};
			sock.onclose = function(){
				me.onclose();
			}
			this.sock = sock;
		} catch(e){
			console.log(e);
		}
	}		
};