'use strict';

var compileTpl     = require('es6-template-strings/compile')
  , resolveTpl     = require('es6-template-strings/resolve-to-string')
  , mano           = require('mano')
  , tryRequire     = require('mano/lib/utils/try-require').bind(require)
  , resolve        = require('path').resolve
  , resolveTrigger = require('./_resolve-trigger')

  , now = Date.now, forEach = Array.prototype.forEach
  , nextTick = process.nextTick
  , stdout = process.stdout.write.bind(process.stdout)
  , StatusLog = mano.db.StatusLog
  , configure, time;

exports = module.exports = [];

configure = function (conf) {
	conf.trigger = resolveTrigger(conf.trigger, conf.triggerValue);
	conf.text = compileTpl(conf.text);
	delete conf.triggerValue;
	conf.variables = Object(conf.variables);
	exports.push(conf);
};

time = now();
stdout("Setup status log...");
mano.apps.forEach(function (app) {
	var conf = tryRequire(resolve(app.root, 'server/status-log'));
	if (!conf) return;
	forEach.call(conf, configure);
});

exports.forEach(function (conf) {
	var onUser = function (user) {
		nextTick(function () {
			var text;
			conf.variables.user = user;
			text = resolveTpl(conf.text, conf.variables);
			delete conf.variables.user;
			user.statusLog.add(new StatusLog({
				label: conf.label,
				official: (conf.official && user[conf.official]) || null,
				time: new Date(Date.now() +
					(conf.timeShift ? (conf.timeShift * 100) : 0)),
				text: text
			}));
		});
	};
	conf.trigger.on('change', function (event) {
		if (event.type === 'add') {
			onUser(event.value);
			return;
		}
		if (event.type === 'delete') return;
		if (event.type === 'batch') {
			if (!event.added) return;
			if (!event.added.size) return;
			event.added.forEach(onUser);
			return;
		}
		console.log("Errorneous event:", event);
		throw new Error("Unsupported event: " + event.type);
	});
});
stdout(" setup in " + ((now() - time) / 1000).toFixed(2) + "s\n");

@@ -11,16 +11,78 @@
 t';%0A%0Avar
+ callable       = require('es5-ext/object/valid-callable')%0A  ,
  compile
@@ -796,16 +796,75 @@
 rValue;%0A
+%09if (conf.resolveUser != null) callable(conf.resolveUser);%0A
 %09conf.va
@@ -1164,20 +1164,22 @@
 %0A%09var on
-User
+Target
  = funct
@@ -1183,20 +1183,22 @@
 nction (
-user
+target
 ) %7B%0A%09%09ne
@@ -1229,16 +1229,138 @@
 var text
+, user;%0A%09%09%09if (conf.resolveUser) user = conf.resolveUser(target);%0A%09%09%09else user = target;%0A%09%09%09conf.variables.target = target
 ;%0A%09%09%09con
@@ -1786,20 +1786,22 @@
  %7B%0A%09%09%09on
-User
+Target
 (event.v
@@ -1981,20 +1981,22 @@
 rEach(on
-User
+Target
 );%0A%09%09%09re

Support non user triggers