/**
 * Module dependencies.
 */

var async = require('async')
var config = require('lib/config')
var app = require('lib/boot')
var serverFactory = require('lib/server-factory')
var notifier = require('democracyos-notifier')
var notifications = require('lib/notifications').notifier
var log = require('debug')('democracyos:server')

module.exports = function listen (opts, callback) {
  var servers = serverFactory(app, opts)

  if (notifications.embedded()) {
    // Start web servers alongside the notifications server
    async.parallel([
      startWebServer,
      startNotificationsService
    ], callback)
  } else {
    // Just start the regular web server
    startWebServer(callback)
  }

  function startWebServer (cb) {
    servers.forEach(function (s) {
      s.listen(function (err) {
        log('Server started at port %s.', s.port)

        cb && cb(err)
      })
    })
  }

  function startNotificationsService (cb) {
    var opts = {
      mongoUrl: config.mongoUrl,
      organizationName: config.notifications.mailer.name,
      organizationEmail: config.notifications.mailer.email,
      mailer: config.notifications.mailer
    }

    log('About to start embedded notifier notifier with options: %j', opts)
    notifier(opts, function (err) {
      if (err) return log('Unexpected error while starting embedded notifications service')

      log('Embedded notifications service started')

      if (cb) cb(err)
    })
  }
}

@@ -377,16 +377,47 @@
 back) %7B%0A
+  callback = callback %7C%7C noop%0A%0A
   var se
@@ -884,14 +884,8 @@
     
- cb &&
  cb(
@@ -1167,39 +1167,118 @@
 iler
+,
 %0A    
-%7D%0A%0A    log('About to s
+  defaultLocale: config.locale,%0A      availableLocales: config.availableLocales%0A    %7D%0A%0A    log('S
 tart
+ing
  emb
@@ -1295,41 +1295,12 @@
 fier
- notifier with options: %25j', opts
+...'
 )%0A  
@@ -1352,14 +1352,17 @@
 rr) 
-return
+%7B%0A       
  log
@@ -1414,25 +1414,48 @@
 tifi
-cations service')
+er', err)%0A        return cb(err)%0A      %7D
 %0A%0A  
@@ -1482,31 +1482,18 @@
 tifi
-cations servic
 e
+r
  started
 ')%0A%0A
@@ -1488,16 +1488,17 @@
  started
+.
 ')%0A%0A    
@@ -1503,22 +1503,11 @@
     
-if (cb) cb(err
+cb(
 )%0A  
@@ -1517,8 +1517,29 @@
 )%0A  %7D%0A%7D%0A
+%0Afunction noop () %7B%7D%0A

add availableLocales on embedded notifier config