/**
 * Created by TalhaAkkas on 15/09/15.
 */

"use strict"
var fs = require('fs');
var langPacks = {};
var path = require('path');
var sprintf = require('sprintf-js').sprintf;
exports.getFunction = function(query){
	try{
		var parts = query.split(".");
		var current = this.langData;
		for(var key in parts){
			if(current[parts[key]]){
				current = current[parts[key]];
			}
		}
		if(typeof current == "string"){
			arguments[0] = current;
			//EWLog(arguments,  sprintf.apply(null, arguments));
			return sprintf.apply(null, arguments);
		}else{
			return query;
		}
	}catch(e){
		return query;
	}
};
exports.swigFilter = function(swig){
	swig.setFilter('word', function(input, idx){
		var args = Array.prototype.slice.call(arguments);
		var lang = args.pop();
		return exports.getFunction.apply({langData: lang}, args);
	});
};
exports.middleware = function(options){
	var langDirectory = options.path || __dirname + "/../../../lang";
	var defaultLang = options.defaultLang || "eng";
	var getLangName = options.getLangName || function(){
			return this.user ? this.user.lang : defaultLang;
		};
	var preloadAllLangs = options.preloadAllLangs || function (){
		fs.readdirSync(langDirectory)
			.filter(function (file) {
				return (file.indexOf(".") !== 0) && (file !== "index.json");
			})
			.forEach(function (file) {
				fs.readFile(langDirectory + "/" + file, 'utf8', function (err, data) {
					if (err) {
						return next(err);
					}
					try{
						langPacks[path.basename(file, '.json')] = JSON.parse(data);
					}catch(e){
						console.log(e);
						console.log(e.stack);
					}finally{
					}
				});
			});
	};
	preloadAllLangs();
	var loadLang = options.loadLang || function(langName, next){
			var that = this;
			if(langPacks[langName]){
				that.langData = langPacks[langName];
				that.locals.langData = langPacks[langName];
				return next();
			}else{
				next(new Error("Default Lang Cannot Be Loaded"));
			}
		};
	return function(req, res, next){
		if(!res.langData || !req.langData){
			if(!res.loadLang){
				res.loadLang = loadLang;
			}
			if(!req.getLangName){
				req.getLangName = getLangName;
			}
			var langName = req.getLangName() || defaultLang;

			res.getWord = exports.getFunction;
			res.loadLang(langName, next);

		}else{
			next();
		}
	};
};