// Generated by CoffeeScript 1.10.0
(function() {
  var bodyParser, compression, cookieSession, createContentServer, express, fs, keys, morgan, once, path, ref;

  express = require('express');

  morgan = require('morgan');

  cookieSession = require('cookie-session');

  bodyParser = require('body-parser');

  ref = require('lodash'), once = ref.once, keys = ref.keys;

  fs = require('fs');

  path = require('path');

  compression = require('compression');

  createContentServer = function(app) {
    var api, server;
    server = express();
    server.use(compression());
    server.set('trust proxy', true);
    server.set('view engine', 'pug');
    server.set('views', app.installDir + '/content-views');
    server.use(morgan('[CONTENT] :method :url :status :response-time ms - :res[content-length]'));
    server.use('/components', express["static"](app.installDir + '/node_modules'));
    server.use('/assets/page', (function(req, res, next) {
      res.set('Cache-Control', 'no-cache');
      return next();
    }), express["static"](path.join(app.installDir, 'content-assets/page'), {
      etag: false,
      lastModified: false
    }));
    server.get('/assets/page/images/random-picture', function(req, res, next) {
      var dir;
      dir = path.join(app.installDir, 'content-assets/page/images');
      return fs.readdir(dir, function(err, files) {
        var imgFiles;
        if (err != null) {
          return res.status(500).end('readdir() failed: ' + String(err));
        }
        imgFiles = files.filter(function(file) {
          return /\.jpe?g/i.test(file);
        });
        return res.sendFile(imgFiles[Math.floor(Math.random() * imgFiles.length)], {
          root: dir,
          lastModified: false,
          cacheControl: false
        });
      });
    });
    server.use('/assets', express["static"](path.join(app.installDir, 'content-assets')));
    server.use(cookieSession({
      name: 'content_session',
      httpOnly: false,
      keys: ['123', '456']
    }));
    server.use(function(req, res, next) {
      var id, uaMatch, userAgent;
      req.device = app.deviceManager.byDeviceId(req.session.deviceId);
      if (req.session.isNew || !req.device) {
        id = Math.random().toString().substring(2);
        req.session.deviceId = id;
        userAgent = req.get('User-Agent');
        req.device = {
          infoHistory: [],
          connectedAt: new Date(),
          address: req.ip,
          userAgent: userAgent,
          deviceId: req.session.deviceId
        };
        if (userAgent && app.config.MobileDetect) {
          uaMatch = app.config.MobileDetect.uaMatch;
          if (uaMatch) {
            req.device.displayName = keys(uaMatch).map(function(key) {
              var category;
              category = uaMatch[key];
              return keys(category).map(function(key) {
                var exp;
                exp = new RegExp(category[key]);
                if (exp.test(userAgent)) {
                  return key;
                }
              }).filter(function(x) {
                return x;
              }).join(' / ');
            }).filter(function(x) {
              return x.length;
            }).join(', ');
          }
        }
        app.deviceManager.add(req.device);
      }
      req.device.lastSeen = new Date();
      req.device.online = true;
      return next();
    });
    server.post('/request-update', bodyParser.json(), function(req, res) {
      var data, dev, hist, i, len, now, oldHist, plannedId, ref1;
      hist = {
        info: req.body.info,
        date: new Date()
      };
      dev = req.device;
      dev.infoHistory.push(hist);
      if (req.body.simulation.running) {
        dev.lastSimInfo = hist;
        dev.firstSimInfo = null;
        now = new Date();
        ref1 = dev.infoHistory;
        for (i = 0, len = ref1.length; i < len; i++) {
          oldHist = ref1[i];
          if (oldHist.date >= now - req.body.simulation.time) {
            dev.firstSimInfo = oldHist;
            break;
          }
        }
        if (dev.firstSimInfo && dev.firstSimInfo.info.battery && dev.lastSimInfo && dev.lastSimInfo.info.battery) {
          dev.ebt = {
            duration: dev.lastSimInfo.date - dev.firstSimInfo.date,
            battery: dev.firstSimInfo.info.battery.level - dev.lastSimInfo.info.battery.level
          };
          if (dev.ebt.battery !== 0 && dev.ebt.duration !== 0) {
            dev.ebt.life = dev.ebt.duration / dev.ebt.battery;
            dev.ebt.remaining = dev.lastSimInfo.info.battery.level * dev.ebt.life;
            dev.ebt.end = new Date(+dev.lastSimInfo.date + dev.ebt.remaining);
          }
        }
      } else {
        req.device.lastSimInfo = null;
        req.device.firstSimInfo = null;
      }
      req.device.info = req.body.info;
      req.device.simulationState = req.body.simulation;
      data = {
        okay: true,
        updateInterval: app.config.deviceConnection.requestUpdateInterval
      };
      plannedId = req.device.plannedSimulationId;
      if (plannedId && (!req.body.simulation || req.body.simulation.id !== plannedId)) {
        data.startSimulation = {
          id: plannedId,
          tasks: app.simulationManager.get(plannedId).tasks
        };
      }
      return res.end(JSON.stringify(data));
    });
    server.get('/', function(req, res) {
      return res.render('index', {
        app: app
      });
    });
    return api = {
      init: function(cb) {
        var httpServer;
        cb = once(cb);
        httpServer = server.listen(app.config.contentServer.port);
        httpServer.once('listening', cb);
        return httpServer.once('error', cb);
      }
    };
  };

  module.exports = createContentServer;

}).call(this);
