/**
 * MainController
 *
 * @module		:: Controller
 * @description	:: Contains logic for handling requests.
 */
var fs = require('fs');

module.exports = {
  /**
   * Client side configs
   * @param  {object} req
   * @param  {object} res
   */
  getConfigsJS: function (req, res) {
    var configs = {};

    // set header to never cache this response
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');

    configs.version = '1';
    configs.server = {};
    configs.client = {};
    configs.client.publicVars = {};
    configs.user = {};
    configs.authenticatedUser = {};

    configs.server.providers = sails.config.wejs.providers;

    // -- Plugin configs
    configs.plugins = {};

    if(sails.config.clientside.loadTypes){
      configs.plugins.loadTypes = sails.config.clientside.loadTypes;
    }

    if(sails.config.clientside.pluginsDefaultEnabled){
      configs.plugins.enabled = sails.config.clientside.pluginsDefaultEnabled;
    }

    // get log config
    configs.client.log = sails.config.clientside.log;

    // get public vars
    if(sails.config.clientside.publicVars) {
      // clone it to dont change global variable
      configs.client.publicVars = _.clone(sails.config.clientside.publicVars);
    }

    configs.client.language = sails.config.i18n.defaultLocale;

    if(!req.isAuthenticated()){
      // send not logged in configs
      return res.send(configs);
    }

    // set current session user auth token and userId
    if( req.session.authToken ) {
      configs.client.publicVars.authToken = req.session.authToken;
      configs.client.publicVars.userId = req.session.userId;
    }

    // get user logged in contacts
    // TODO DEPRECATED remove this Contact.getUserContacts getter
    Contact.getUserContacts(req.user.id, function(err, contacts){
      if (err) return res.negotiate(err);
      configs.authenticatedUser.contacts = contacts;
      res.send(configs);
    });

  },

  getTranslations: function (req, res) {
    var localeParam = req.param('locale');
    var locale;

    if (localeParam) {
      // check if the locale are in avaible we.js locales
      // TODO add suport to search in subprojects
      for (var i = sails.config.i18n.locales.length - 1; i >= 0; i--) {
        if(sails.config.i18n.locales[i] === localeParam){
          locale = localeParam;
        }
      }
    }

    if(req.isAuthenticated()){
      locale = req.user.language;
    }

    if(!locale){
      locale = sails.config.i18n.defaultLocale;
    }

    var translationResponse = '';

    translationResponse += 'if(typeof Ember === "undefined"){' +
      'Ember = {};' +
      'Ember.I18n = {};' +
    '}\n';

    translationResponse += 'if(!Ember.I18n.translations){' +
      'Ember.I18n.translations = {};' +
    '}\n';


    getTranslationFilePath(locale , function(path){
      if (path) {
        fs.readFile(path, 'utf8', function (err, data) {
          if (err) {
            sails.log.error('Error: ' + err);
            return res.serverError();
          }

          translationResponse += 'Ember.I18n.translations = ';
          translationResponse+= data;
          translationResponse += ';';

          res.contentType('application/javascript');
          res.send(200, translationResponse );
        });
      } else {
        sails.log.debug('getTranslations:Locale not found:', locale, localeParam);
        res.contentType('application/javascript');
        res.send(200, translationResponse );
      }

    });

  }
};

function getTranslationFilePath (locale, callback) {
  var localePath = null;
  // check if exists in project
  localePath = sails.config.appPath + '/config/locales/' + locale + '.json';
  fs.exists(localePath, function (exists) {
    if(exists){
      return callback(localePath);
    }

    // if dont have in project use we.js default translations
    localePath = sails.config.appPath + '/node_modules/we-plugin-core/config/locales/' + locale + '.json';
    fs.exists(localePath, function (exists) {
      if(exists){
        return callback(localePath);
      }
      sails.log.info('Localization not found in project or sub-project for', locale);
      callback();
    });
  });
}


@@ -128,16 +128,43 @@
 e('fs');
+%0Avar _ = require('lodash');
 %0A%0Amodule
@@ -320,24 +320,52 @@
 onfigs = %7B%7D;
+%0A    var sails = req._sails;
 %0A%0A    // set
@@ -792,320 +792,8 @@
 s;%0A%0A
-    // -- Plugin configs%0A    configs.plugins = %7B%7D;%0A%0A    if(sails.config.clientside.loadTypes)%7B%0A      configs.plugins.loadTypes = sails.config.clientside.loadTypes;%0A    %7D%0A%0A    if(sails.config.clientside.pluginsDefaultEnabled)%7B%0A      configs.plugins.enabled = sails.config.clientside.pluginsDefaultEnabled;%0A    %7D%0A%0A
     
@@ -1128,24 +1128,190 @@
 ultLocale;%0A%0A
+    if (sails.config.auth) %7B%0A       configs.client.isProvider = sails.config.auth.isProvider;%0A       configs.client.isConsumer = sails.config.auth.isConsumer;%0A    %7D%0A%0A
     if(!req.
@@ -1632,272 +1632,8 @@
  %7D%0A%0A
-    // get user logged in contacts%0A    // TODO DEPRECATED remove this Contact.getUserContacts getter%0A    Contact.getUserContacts(req.user.id, function(err, contacts)%7B%0A      if (err) return res.negotiate(err);%0A      configs.authenticatedUser.contacts = contacts;%0A  
     
@@ -1651,25 +1651,16 @@
 nfigs);%0A
-    %7D);%0A%0A
   %7D,%0A%0A  

update get configs