package se.l4.dust.core.internal.template;

import se.l4.dust.api.Context;
import se.l4.dust.api.messages.MessageManager;
import se.l4.dust.api.messages.Messages;
import se.l4.dust.api.resource.variant.ResourceVariant;
import se.l4.dust.api.template.RenderingContext;
import se.l4.dust.api.template.dom.DynamicContent;
import se.l4.dust.api.template.dom.Text;
import se.l4.dust.api.template.dom.VariantContent;
import se.l4.dust.api.template.spi.PropertySource;
import se.l4.dust.api.template.spi.TemplateInfo;
import se.l4.dust.api.template.spi.TemplateVariant;

import com.google.inject.Inject;

public class MessagePropertySource
	implements PropertySource
{
	private static final String VARIANT_KEY = "__variant__";
	
	private final MessageManager messageManager;
	
	@Inject
	public MessagePropertySource(MessageManager messages)
	{
		this.messageManager = messages;
	}
	
	public DynamicContent getPropertyContent(TemplateInfo namespaces,
			Class<?> context, 
			String propertyExpression)
	{
		return new Content(namespaces.getURL(), propertyExpression);
	}
	
	private class Content
		extends DynamicContent
		implements VariantContent
	{
		private final String url;
		private final String property;

		public Content(String url, String property)
		{
			this.url = url;
			this.property = property;
		}
		
		@Override
		public Object getValue(RenderingContext ctx, Object root)
		{
			Messages messages = getMessages(ctx);
			return messages.get(property);
		}

		private Messages getMessages(Context ctx)
		{
			Messages messages;
			if(ctx.getValue(url) != null)
			{
				messages = ctx.getValue(url);
			}
			else
			{
				messages = messageManager.getMessages(ctx, url);
				ctx.putValue(url, messages);
			}
			
			return messages;
		}

		@Override
		public void setValue(RenderingContext ctx, Object root, Object data)
		{
			
		}
		
		public se.l4.dust.api.template.dom.Content copy()
		{
			return new Content(url, property);
		}

		public void transform(TemplateVariant variant)
		{
			Messages messages = getMessages(variant.getContext());
			Text text = new Text(messages.get(property));
			ResourceVariant rv = messages.getVariant();
			variant.replaceWith(text, rv);
		}
	}
}

@@ -60,32 +60,73 @@
 st.api.Context;%0A
+import se.l4.dust.api.TemplateException;%0A
 import se.l4.dus
@@ -1462,30 +1462,38 @@
 es(ctx);%0A%09%09%09
-return
+String value =
  messages.ge
@@ -1497,32 +1497,184 @@
 .get(property);%0A
+%09%09%09if(value == null)%0A%09%09%09%7B%0A%09%09%09%09throw new TemplateException(%22The property %22 + property + %22 does not exist in the file %22 + url);%0A%09%09%09%7D%0A%09%09%09%0A%09%09%09return value;%0A
 %09%09%7D%0A%0A%09%09private M

Enforce finding of messages