package kimiko.japonais.app.data.tools;

import java.util.List;

import kimiko.japonais.app.data.Mot;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class MotLoader extends DefaultHandler {
	private List<Mot> mots;
	private String japonais, kana, type, trad;
	private StringBuffer buffer;

	public MotLoader(List<Mot> mots) {
		this.mots = mots;
	}


	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equals("mots")) {
		} else if (qName.equals("mot")) {
			japonais = kana = type = trad = "";
		} else {
			buffer = new StringBuffer();
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals("mots")) {
		} else if (qName.equals("mot")) {
			//String rom = (kana==null)? japonais:kana;
			synchronized(this.mots) {
				this.mots.add(new Mot(japonais, kana, "", trad, type));
			}
			Log.v(this.getClass().getSimpleName(), "taille : " + this.mots.size());
		} else if (qName.equals("jap")) {
			this.japonais = buffer.toString();
			buffer=null;
		} else if (qName.equals("kana")) {
			this.kana = buffer.toString();
			buffer=null;
		} else if (qName.equals("trad")) {
			this.trad = buffer.toString();
			buffer=null;
		} else if (qName.equals("type")) {
			this.type = buffer.toString();
			buffer=null;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String lecture = new String(ch, start, length);
		if (buffer != null)
			buffer.append(lecture);
	}
}
