; (function (window) {
	var App = window.App || {}
	var url = null

	function NewSocket(option) {
		url = option.url
		this.ws = new WebSocket(option.url)
		this.message = option.message || '0'
		this.interval = option.interval || 3000
		this.onmessageHandle = option.onmessageHandle || function () { }
		this.onopenHandler = option.onopenHandler || function () { }
		this.oncloseHandler = option.oncloseHandler || function () { }

		this.state = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']

		this.ws.onmessage = function (e) {
			// console.info('recive message:', e)
			this.onmessageHandle(e.data)
		}.bind(this)

		this.ws.onopen = function (e) {
			// TODO: 先发一个心跳再去执行setInterval 待修改心跳方法后完善去掉
			this.sendMessage(
				JSON.stringify(1)
			)
			this.startHeart()
			this.onopenHandler(e)
		}.bind(this)

		this.ws.onclose = function (e) {
			this.oncloseHandler(e)
			console.warn('websocket is closed.', e)
		}.bind(this)
	}

	NewSocket.prototype.sendMessage = function (message) {
		if (this.ws.readyState === 1) {
			this.ws.send(message)
		} else {
			this.closeSocket()
		}
	}

	// 设置发送的消息
	NewSocket.prototype.setMessage = function (message) {
		this.message = message
	}

	// 开始心跳
	NewSocket.prototype.startHeart = function () {
		this.heartTimer = setInterval(
			function () {
				this.sendMessage(1)
			}.bind(this),
			this.interval
		)
	}

	// 停止心跳
	NewSocket.prototype.stopHeart = function () {
		clearInterval(this.heartTimer)
	}

	// 关闭连接
	NewSocket.prototype.closeSocket = function () {
		this.ws.close()
		clearInterval(this.heartTimer)
	}

	App.NewSocket = NewSocket
	window.App = App
})(window)
