import { formatLog } from './loghelper.mjs'
import { getStatus, safeWrap } from '../util.mjs'

export default function coremonitor(io, ctx) {
  
  ctx.core.applications.forEach(function(app) {
    app.on('updating', safeWrap(ctx.log, `${app.name}.on('updating')`, function() {
      io.emit('core.status', getStatus(ctx))
    }))
    app.on('running', safeWrap(ctx.log, `${app.name}.on('updating')`, function() {
      io.emit('core.status', getStatus(ctx))
    }))

    app.on('updatelog', safeWrap(ctx.log, `${app.name}.on('updatelog')`, function(loglines) {
      io.to(`app.${app.name}`).emit('app.updatelog', {
        name: app.name,
        log: loglines,
      })
    }))

    if (app.name !== ctx.app.name) {
      app.ctx.log.on('newlog', safeWrap(ctx.log, `${app.name}.log.on('newlog')`, function(data) {
        io.to('logger.' + app.name).emit('newlog', formatLog(data))
      }))
    }
  })

  ctx.core.log.on('newlog', safeWrap(ctx.log, `core.log.on('newlog')`, function(data) {
    io.to('logger.service-core').emit('newlog', formatLog(data))
  }))

  ctx.log.on('newlog', safeWrap(ctx.log, 'coremonitor.on.newlog', function(data) {
    // Stop infinite regression
    if (data?.err?.signal === 'newlogerror') return
    try {
      io.to('logger.' + ctx.app.name).emit('newlog', formatLog(data))
    } catch (err) {
      err.signal = 'newlogerror'
      throw err
    }
  }))

  /*
  log.on('newlog', safeWrap(log, 'coremonitor.on.newlog', function(data) {
    io.to('logger').emit('newlog', formatLog(data))
  }))
  core.on('dbupdated', safeWrap(log, 'coremonitor.on.dbupdated', function() {
    io.to('core').emit('core.db', db.get('core').value())
  }))
  core.on('statusupdated', safeWrap(log, 'coremonitor.on.statusupdated', function() {
    io.to('core').emit('core.status', core.status())
  }))
  core.on('applog', safeWrap(log, 'coremonitor.on.applog', function(app) {
    io.to('core.app').emit('core.program.log', {
      name: 'app',
      logs: app.logs,
    })
  }))
  core.on('managelog', safeWrap(log, 'coremonitor.on.managelog', function(manage) {
    io.to('core.manage').emit('core.program.log', {
      name: 'manage',
      logs: manage.logs,
    })
  }))*/
}
