package j3deditor.bin.util;

import java.io.File;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 * Tool for translating UI text
 * to specified language.
 *
 * Uses document tree loaded from an XML file.
 *
 * @author Risto Seene
 */
public class Translator{

	/** Root node of document tree */
	private Node root;


	/**
	 * Create an instance of <code>Translator</code>.
	 *
	 * @param language
	 *	two letter language code in lower case
	 */
	public Translator(String language){
		try{
			if(language.equals("default")){
				loadDefault();
			} else {
				this.root = new XMLParser(UserData.getFile(UserData.languages + File.separator + "lang_" + language + ".xml")).getRoot();
			}
		} catch(Throwable t){
			Utilities.out.throwWarning(t);
			loadDefault();
		}
	}


	/**
	 * Loads the default translation file.
	 */
	private void loadDefault(){
		try{
			this.root = new XMLParser(Utilities.util.getResource(Utilities.defaultData + "lang_default.xml")).getRoot();
		} catch(Throwable t){
			Utilities.out.throwFatalError(t);
		}
	}


	/**
	 * Returns descendant of <code>className</code> which
	 * name is <code>object</code>.
	 *
	 * @param className
	 *	the name of class the object is defined in
	 * @param object
	 *	the name of the object
	 * @return Returns descendant of <code>className</code>
	 *	which name is <code>object</code>
	 */
	private Node getNode(String className, String object) throws Exception{
		String[] nodes = className.replace(".", " ").split(" ");
		Node activeNode = root;

		for(int i = 0; i < nodes.length; i++){
			NodeList nodeList = ((Element)activeNode).getElementsByTagName(nodes[i]);

			for(int j = 0; j < nodeList.getLength(); j++){
				if(nodeList.item(j).getParentNode().getNodeName().equals(activeNode.getNodeName())){
					activeNode = nodeList.item(j);
					break;
				}
			}
		}

		return ((Element)activeNode).getElementsByTagName(object).item(0).getFirstChild();
	}


	/**
	 * Returns translation of element which name is <code>object</code> and
	 * which is located inside <code>cl</code> class.
	 *
	 * @param cl
	 *	the name of the class the object is defined in
	 * @param object
	 *	the name of the object
	 * @return Returns an instance of <code>String</code> that contains translation
	 */
	public String translate(Class cl, String object){
		String translation = null;

		try{
			translation = getNode(cl.getName(), object).getNodeValue();
		} catch(Throwable t){
		}

		if(translation == null){
			return "[" + object + "]";
		}
		return translation;
	}

}
