package kimiko.japonais.app.data.tools;

import java.util.List;

import kimiko.japonais.app.data.Exemple;

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

import android.util.Log;

public class ExempleLoader extends DefaultHandler {
	private List<Exemple> exemples;
	private String japonais, rom, meaning;
	private StringBuffer buffer;

	public ExempleLoader(List<Exemple> exemples) {
		this.exemples = exemples;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equals("phrases")) {
		} else if (qName.equals("phrase")) {
			japonais = rom  = meaning = "";
		} else {
			buffer = new StringBuffer();
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals("phrases")) {
		} else if (qName.equals("phrase")) {
			synchronized(this.exemples) {
			    this.exemples.add(new Exemple(japonais, rom, meaning));
			}
			Log.v(this.getClass().getSimpleName(), "taille : " + exemples.size());
		} else if (qName.equals("japonais")) {
			this.japonais = buffer.toString();
			buffer=null;
		} else if (qName.equals("romanisation")) {
			this.rom = buffer.toString();
			buffer=null;
		}
		else if (qName.equals("francais")) {
			this.meaning = 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);
	}
}
