module.exports = function(options, callback) {

    options = options || {};
    var port = options.port;

    var path = require('path'),
        webServer = require('./webapp/routes.js'),
        helpers = require('./helpers'),
        jobs_manager = require('./job-manager'),
        http = require('http'),
        fs = require('fs'),
        generalConfigManager = require('./config-manager')(),
        loadGlobalAuth = require('./global-auth'),
        packageDependencyManager = require('./package-dependency-manager');

    var packagesLocalFolder = path.join(process.cwd(), "/packages");
    var packagesAtlasboardFolder = path.join(__dirname, "../packages");

    var configPath = path.join(process.cwd(), "/config");

    //-----------------------------------
    // Global config
    //-----------------------------------
    http.globalAgent.maxSockets = 100;

    //-----------------------------------
    // Runner
    //-----------------------------------

    var runner = function() {
      //-----------------------------------
      // Init web server
      //-----------------------------------
      var app = require('express')();
      webServer(app, port, [packagesLocalFolder, packagesAtlasboardFolder], generalConfigManager);

      var httpServer = http.createServer(app).listen(app.get('port'));
      var assignedPort = app.get('port');
      if (!assignedPort){
        return callback('Error initializating web server on port ' + port +
          '. Please check that the port is not in use and you have the ' +
          'right permissions.');
      }
      console.log("\n   AtlasBoard server started. Go to: http://localhost:" + assignedPort + " to access your dashboard \n");


      //-----------------------------------
      // Init socket.io server
      //-----------------------------------
      var io = require('socket.io').listen(httpServer, {
          'log level': 2
      });
      var startTime = new Date().getTime();
      io.on('connection', function (socket) {
        socket.emit("serverinfo", {startTime: startTime});
      });


      //-----------------------------------
      // Init jobs / scheduler
      //-----------------------------------
      var eventQueue = require(path.join(__dirname, "event-queue"))(io);
      var scheduler = require(path.join(__dirname, "scheduler")).scheduler;

      // Needed for hot scheduling job of newly added widgets.
      scheduler.eventQueue = eventQueue;
      scheduler.io = io;

      var generalLogger = require('./logger')();


      var jobOptions = {
        packagesPath : [packagesLocalFolder, packagesAtlasboardFolder],
        configPath: configPath,
        filters: options.filters
      };

      jobs_manager.get_jobs(jobOptions, function(err, jobWorkers){
        if (err) return callback(err);


        if (!jobWorkers.length){
          generalLogger.warn("No jobs found matching the current configuration and filters");
        }
        else {
          jobWorkers.forEach(function (jobWorker){
            scheduler.scheduleFirst(jobWorker,true);
          });
        }

        return callback();
      });
    };


    if(options.install) {
      packageDependencyManager.installDependencies([packagesLocalFolder], function(err){
        if (err) return callback(err);
        runner();
      });
    } else {
      runner();
    }

};

