/**
 * Localisation directive. Can be used as follows:
 *
 * <lmsg src="localisation.key">Default text</lmsg>
 * will generate "Localised text" if the key is defined or remain the same and display "Default text" if it is not defined
 *
 * or
 *
 * * <element attr1="x" attr2="y" lmsg="localisation.key">Default Text</element>
 * will generate
 * <element attr1="x" attr2="y">Localised Text</element>
 *
 * or
 *
 * <element attr1="x" attr2="y" lmsg="title:localisation.key">Default Text</element>
 * will generate
 * <element attr1="x" attr2="y" title="Localised text">Default Text</element>
 *
 * Localisation strings must be loaded via the usual js_localize component from strings in the 'lm' format
 */
define(['cla_angular'], function (angular) {
	var moduleName = 'cla.core.lmsg';
	var module;
	try {
		module = angular.module(moduleName);
	} catch(err) {
		// named module does not exist, so create one
		module = angular.module(moduleName, []);
	}

	module.directive('lmsg', function() {
		return {
			restrict: 'EA',
			replace: true,
			controllerAs: 'lmsg',
			bindToController: true,
			compile: function(elem, attrs)
			{
				var value = '';
				if (elem[0].nodeName === 'LMSG')
				{
					// This is an <lmsg> element, so completely replace it
					value = lmsg(attrs.src);
					if ((value !== attrs.src) &&
						(value !== undefined))
					{
						elem.replaceWith(value);
					}
				} else
				{
					// An lmsg attribute
					var parts = attrs.lmsg.split(':', 2);

					var target = 'body';
					if (parts.length == 1)
					{
						// No target attribute
						value = lmsg(parts[0]);
						if (value !== undefined)
							elem.text(value);
					}
					if (parts.length == 2)
					{
						// Has a target attribute
						target = parts[0];
						value = lmsg(parts[1]);

						if (value !== undefined)
							elem.attr(target, value);
					}
				}
			}
		};
	});
});