import store from '../store'
let websocket = null
let commit = null

export function createSoceket(options) {
  if (options) {
    commit = options.commit
  }
  // 判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    if (websocket === null) {
      websocket = new WebSocket(process.env.VUE_APP_SOCKET_SERVER)
      init()
    }
  } else {
    alert('Not support websocket')
  }
}

export function init() {
  // 连接发生错误的回调方法
  websocket.onerror = function() {
    commit(`SET_SCOKET_STATE`, false)
    console.log('socket connect with error !')
  }

  // 连接成功建立的回调方法
  websocket.onopen = function(event) {
    commit(`SET_SCOKET_STATE`, true)
    console.log('socket is open !')
  }

  // 接收到消息的回调方法
  websocket.onmessage = function(event) {
    console.log(event.data)
    commit(`UPDATE_MESSAGE`, JSON.parse(event.data))
    console.log(store.getters.messageList)
  }

  // 连接关闭的回调方法
  websocket.onclose = function() {
    commit(`SET_SCOKET_STATE`, false)
    console.log('socket is closed !')
  }
}

// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function() {
  websocket && websocket.close()
}

// 关闭连接
export function closeWebSocket() {
  websocket && websocket.close()
}

// 发送消息
export function send() {
  var message = document.getElementById('text').value
  websocket.send(message)
}

