import * as core from './core/ioroutes.mjs'
import { getConfig, getStatus } from './util.mjs'

function register(ctx, name, method) {
  if (typeof(method) === 'object') {
    Object.keys(method).forEach(key => {
      register(ctx, [name, key].join('.'), method[key])
    })
    return
  }

  ctx.socket.on(name, async function(data, cb) {
    ctx.log.debug('SocketIO: ' + name)

    try {
      await method(ctx, data, cb)
    }
    catch (error) {
      ctx.log.error(error, `Error processing ${name}`)      
    }
  })
}


function onConnection(server, ctx, data) {
  const io = server
  const socket = data

  const child = ctx.log.child({
    id: socket.id,
  })
  child.event = ctx.log.event

  child.info('Got new socket connection')

  let ioCtx = {
    io: io,
    socket: socket,
    log: child,
    db: ctx.db,
    core: ctx.core,
    logroot: ctx.log,
  }

  ioCtx.socket.on('disconnect', function() {
    child.info('Closed connection')
  })

  register(ioCtx, 'core', core)

  ioCtx.socket.emit('core.config', getConfig(ioCtx))
  ioCtx.socket.emit('core.status', getStatus(ioCtx))
}

export default onConnection
