package Cluedo.API;

import java.io.File;
import java.util.Hashtable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Loads, parses and interprets a language pack
 * 
 * @author Alex
 */
public class LanguagePackReader {
	Hashtable groups = new Hashtable();
	Hashtable group;
	
	LanguageBinding binding = new LanguageBinding();
	String currentGroup = "";
	String lastSection = "";
	String language = "";
	
	DefaultHandler messageParser = new DefaultHandler() {
		LanguageBinding currentBinding;
		
		public void characters(char [] buf, int offset, int len) {	
			String s = new String(buf, offset, len);
			s = s.trim();
			if(s.equals(""))
				return;
			if(lastSection.equals("message")) {
				currentBinding.message=s;
				group.put(currentBinding.function, currentBinding);
			}
		}

		public void endElement(String namespaceURI, String localName, String qName) {

			if(qName.equals("group")) {
				groups.put(currentGroup, group);
			}
		}

		public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
			lastSection = qName;
			if(qName.equals("messages")) {
				language = atts.getValue(0);
				System.out.println("[LanguagePackReader:readLanguage] Language type: " + language + ", author " + atts.getValue(1));
			}
			if(qName.equals("group")) {
				group = new Hashtable();
				currentGroup = atts.getValue(0);
			}
			else if(qName.equals("message")) {
				currentBinding = new LanguageBinding();
				currentBinding.function = atts.getValue(0);
			}
	
		}

	};
	
	
	/**
	 * @param pack
	 * @return
	 */
	public Hashtable readLanguage(File pack) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();

			saxParser.parse( pack.getAbsolutePath(), messageParser );
		}
		catch (Exception e) {
			e.printStackTrace();
		}

		return groups;
	}


}
