package net.psammead.commonist.util;

import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;

import net.psammead.util.*;

/** encapsulates user messages loaded from a properties document */
public class Messages {
	private static Messages	SELF	= null;
	
	public static void init(URL url) throws IOException {
		SELF	= new Messages(url);
	}
	
	public static String text(String key) {
		return SELF.getText(key);
	}
	
	public static String message(String key, Object[] args) {
		return SELF.getMessage(key, args);
	}
	
	//------------------------------------------------------------------------------
	
	private static final Logger log = new Logger(Messages.class);
	 
	private Properties	props;
	
	/** fully static utility class, shall not be instantiated */
	public Messages(URL url) throws IOException {
		InputStream	in	= null;
		try {
			in		= url.openStream();
			props	= new Properties();
			props.load(in);
		}
		finally {
			if (in != null)
			try { in.close(); }
			catch (Exception e) { log.error("cannot close", e); }
		}
	}

	public String getText(String key) {
		String	text	= props.getProperty(key);
		if (text == null)	throw new RuntimeException("text: " + key + " not available");
		return text;
	}
	
	public String getMessage(String key, Object[] args) {
		String	message	= props.getProperty(key);
		if (message == null)	throw new RuntimeException("message: " + key + " not available");
		return MessageFormat.format(message, args);
	}
}
