package android.langue.furansugo.dic;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

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

import org.xml.sax.SAXException;

public class Dictionnaire {
	private static List<Mot> mots;
	
	public Dictionnaire(InputStream stream) {
		if(mots == null) {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			try {
				SAXParser parseur = factory.newSAXParser();
				MotsHandler gestionnaire = new MotsHandler();
				parseur.parse(stream, gestionnaire);
				mots = gestionnaire.getDictionnaire();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public Mot hasard() {
		if(mots == null) return null;
			return mots.get(new Random().nextInt(mots.size()));
	}
	
	public List<Mot> chercher(String key)
	{
		if(mots == null) return null;
		List<Mot> result = new ArrayList<Mot>();
		for(Mot mot : mots)
			if(mot.getJap().contains(key) || mot.getKana().contains(key) || mot.getTrad().contains(key))
				result.add(mot);
		return result;
	}
}
