// Generated by CoffeeScript 1.8.0
var Account, CONSTANTS, Contact, Scheduler, Settings, async, cozydb, log, ramStore;

Scheduler = require('../processes/_scheduler');

Account = require('../models/account');

Contact = require('../models/contact');

Settings = require('../models/settings');

CONSTANTS = require('../utils/constants');

async = require('async');

cozydb = require('cozy-db-pouchdb');

log = require('../utils/logging')({
  prefix: 'controllers:index'
});

ramStore = require('../models/store_account_and_boxes');

module.exports.main = function(req, res, next) {
  if (Scheduler.applicationStartupRunning()) {
    return res.render('reindexing');
  }
    }, function(cb) {
      return cozydb.api.getCozyLocale(cb);
    }, function(cb) {
      return cb(null, ramStore.clientList());
    }, function(cb) {
      return Contact.list(cb);
    }
  ], function(err, results) {
    var accounts, contacts, imports, locale, refreshes, settings;
    refreshes = Scheduler.clientSummary();
    if (err) {
      log.error("err on index", err.stack);
      imports = "console.log(\"" + err + "\");\nwindow.locale = \"en\"\nwindow.refreshes = []\nwindow.accounts  = []\nwindow.contacts  = []";
    } else {
      settings = results[0], locale = results[1], accounts = results[2], contacts = results[3];
      imports = "window.settings  = " + (JSON.stringify(settings)) + "\nwindow.refreshes = " + (JSON.stringify(refreshes)) + ";\nwindow.locale    = \"" + locale + "\";\nwindow.accounts  = " + (JSON.stringify(accounts)) + ";\nwindow.contacts  = " + (JSON.stringify(contacts)) + ";\nwindow.app_env   = \"" + process.env.NODE_ENV + "\";";
    }
    return res.render('index', {
      imports: imports
    });
  });
};

module.exports.refresh = function(req, res, next) {
  var limitByBox, onlyFavorites, _ref;
  if ((_ref = req.query) != null ? _ref.all : void 0) {
    limitByBox = null;
    onlyFavorites = false;
  } else {
    limitByBox = CONSTANTS.LIMIT_BY_BOX;
    onlyFavorites = true;
  }
  return Scheduler.startAllRefresh(function(err) {
    if (err) {
      log.error("REFRESHING ACCOUNT FAILED", err);
    }
    if (err) {
      return next(err);
    }
    return res.send({
      refresh: 'done'
    });
  });
};

module.exports.refreshes = function(req, res, next) {
  return res.send(Scheduler.clientSummary());
};
  return async.series([
    function(cb) {
      return Settings.getDefault(cb);