import JSEncrypt from 'jsencrypt'
import { getToken } from './auth'

let socket = null
let socketInterval = null
const EncryptHandler = new JSEncrypt()
const SockEventMap = { 'pon': undefined }

// wss://wine.ifarmcloud.com/api/manager/socket, ws://192.168.1.6:3080/admin/manager
const ServerPrefix = 'ws://192.168.1.6:3080/worker/socket'
const SendWss = (event, data, ttl) => {
  if (socket !== null) return socket.send(JSON.stringify({ event, data }))
  if (ttl === undefined) ttl = 3
  if (ttl > 0) setTimeout(() => SendWss(event, data, ttl - 1), 1000)
}
const ConnectSocket = () => {
  const url = `${ServerPrefix}/${getToken()}`
  socket = new WebSocket(url)
  socket.onclose = () => {
    socket = null
    ConnectSocket()
  }
  socket.onopen = () => {
    clearInterval(socketInterval)
    socketInterval = setInterval(() => SendWss('pin', null), 50 * 1000)
  }
  socket.onmessage = event => {
    const body = JSON.parse(event.data)
    SockEventMap[body.event] && SockEventMap[body.event](body.data)
  }
}
const CloseSocket = () => {
  if (socket === null) return
  socket.close()
}

export default {
  EncryptHandler, SockEventMap,
  ConnectSocket, SendWss, CloseSocket
}
