import * as SocketIO from 'socket.io'
import * as Events from 'events'
import execCommand from './util/execCommand'

let isExecting = false
/**
 * 处理CMD相关事件
 * @param socket
 */
export default function registerCmdHandler(socket: SocketIO.Socket) {
   // 执行CMD指令
  socket.on('cmd.exec', (
    cmd: string,
    args: Array<string>,
    targetDir: string | undefined
  ) => {
    if (isExecting) {
      socket.emit('cmd.error', {
        message: 'server block: only one command can execute at one time'
      })
      return
    }
    isExecting = true

    let cmdEvent: Events
    try {
      cmdEvent = execCommand(cmd, args, targetDir)
    } catch (e) {
      socket.emit('cmd.error', {
        message: e.message
      })
      return
    }
    cmdEvent.on('data', (data) => {
      socket.emit('cmd.output', data)
    })
    cmdEvent.on('error', (error) => {
      isExecting = false
      socket.emit('cmd.error', {
        message: error.message
      })
    })
    cmdEvent.on('done', () => {
      isExecting = false
      socket.emit('cmd.end')
    })
  })
}