import { io } from 'socket.io-client'

const URL = 'http://localhost:3000'

process.env.NODE_ENV === 'production' ? undefined : 'http://localhost:3001'

const ioOpts = {
  // timeout: 300 * 1000,
  // reconnectionDelay: 5000 // defaults to 1000
  // reconnectionDelayMax: 10000 // defaults to 5000reconnection: true, // Enable reconnection
  reconnectionAttempts: Infinity, // Maximum number of reconnection attempts
  reconnectionDelay: 1000, // Time between each attempt (in ms)
  reconnectionDelayMax: 5000, // Maximum time between attempts (in ms)
  randomizationFactor: 0.5, // Randomization factor for the delay
  timeout: 20000, // Connection timeout (in ms)
}
// const socket = URL === undefined ? io(ioOpts) : io(URL, ioOpts)
const socket = io('http://localhost:3000', ioOpts)

socket.on('connect', () => {
  if (socket.recovered) {
    console.log('SOCKET: socket recovered succesfully')
  } else {
    console.log('SOCKET: socket connected')
  }

  // setTimeout(() => {
  //   socket.io.engine.close()
  // }, 60 * 1000)
})

export default {
  socket,
  sendMessage(event: any, data: any) {
    socket.emit(event, data)
  },
  async sendMessageWithAck(event: any, data: any) {
    return await socket.emitWithAck(event, data)
  },
  onMessage(event: any, callback: any) {
    socket.on(event, callback)
  },
  disconnect() {
    socket.disconnect()
  },
}
