import defaults from './defaults.mjs'

export function safeWrap(log, name, fn) {
  return function(data, cb) {
    try {
      let out = fn(data, cb)
      if (out && out.then) {
        out.then(function() {}, function(err) {
          log.error(err, 'Unknown error in ' + name)
          log.event.error('Unknown error occured in ' + name + ': ' + err.message)
        })
      }
    } catch (err) {
      log.error(err, 'Unknown error in ' + name)
      log.event.error('Unknown error occured in ' + name + ': ' + err.message)
    }
  }
}

export function getConfig(ctx) {
  let merge = {
    applications: [],
    name: ctx.db.config.name || '',
    title: ctx.db.config.title || '',
  }
  for (let app of ctx.core.applications) {
    merge[app.name] = {
      provider: app.config.provider || null,
      url: app.config.url || null,
      port: app.config.port || null,
      scAllowStop: app.config.scAllowStop || null,
    }
    merge.applications.push(app.name)
  }
  return merge
}

export function getApp(ctx, name, action) {
  let app = ctx.core.applicationMap.get(name)

  if (!app) {
    ctx.log.warn(`Invalid action ${action} on non-existing app ${name}`)
    ctx.log.event.warn(`Invalid action ${action} on non-existing app ${name}`)
    return null
  }
  if (action === 'start' && !app.config.scAllowStop && app.running) {
    ctx.log.warn(`Invalid action ${action} on existing app ${name}`)
    ctx.log.event.warn(`Invalid action ${action} on existing app ${name}`)
    return null
  }
  return app
}

const lastAction = {

}

export function stopSpam(ctx, action, name) {
  let key = name + '.' + action
  var d = new Date()
  if (!lastAction[key]) {
    lastAction[key] = d
    return false
  }
  if (d - lastAction[key] < 1000 * 60 * 1) {
    ctx.log.warn(`${action} called too fast on ${name}`)
    ctx.log.event.warn(`${action} called too fast on ${name}`)
    return lastAction[key]
  }
  lastAction[key] = d
  return false
}

export function getStatus(ctx) {
  let status = {}
  for (let app of ctx.core.applications) {
    if (app.provider.static) {
      status[app.name] = {
        active: 'static',
        latestInstalled: 'static',
        updated: '',
        running: app.running,
        updating: false,
      }
    } else {
      let appDb = ctx.db.data.core[app.name]
      let active = ctx.db.get(appDb.versions, appDb.active)
      let installed = ctx.db.get(appDb.versions, appDb.latestInstalled)
      status[app.name] = {
        active: active,
        latestInstalled: installed,
        updated: appDb.updater,
        running: app.running || app.ctx.version,
        updating: app.updating,
      }
    }
  }
  return status
}
