import * as SocketIO from 'socket.io'
import * as http from 'http'

import registerCmdHandler from './cmdHandler'
import registerCliHandler from './cliHandler'

export default function createSocket(server: http.Server) {
  const io = SocketIO(server)
  
  registerEventListener(io.of('/cmd'))
}

function registerEventListener(io: SocketIO.Namespace) {
  let currentAddress: string | null

  io.on('connect', function(socket){
    // 当前一个地址仅允许一个客户端
    if(currentAddress) {
      socket.emit('blocked')
    }
    currentAddress = socket.handshake.address
    socket.on('disconnect', () => {
      currentAddress = null
    })
    // 绑定事件处理
    registerCmdHandler(socket)
    registerCliHandler(socket)
    socket.emit('connect')
  })
}