package kimiko.japonais.app.data;

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

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

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

import kimiko.japonais.app.data.tools.ExempleLoader;
import kimiko.japonais.app.data.tools.MotLoader;
import kimiko.japonais.app.R;

import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DatabaseHandler extends SQLiteOpenHelper {
	private Context context;

	public DatabaseHandler(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Toast.makeText(this.context, context.getResources().getString(R.string.chargement_debut), Toast.LENGTH_LONG).show();
		Log.v(this.getClass().getSimpleName(), "Creation de la base.");
		try {

			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			List<Mot> mots = new ArrayList<Mot>();
			DefaultHandler handler = new MotLoader(mots);
			parser.parse(context.getResources().openRawResource(R.raw.mots),
					handler);

			MotDAO.creer(db);
			for (Mot m : mots)
				MotDAO.ajouter(m, db);
			
			List<Exemple> exemples = new ArrayList<Exemple>();
			DefaultHandler handler1 = new ExempleLoader(exemples);
			parser.parse(context.getResources().openRawResource(R.raw.exemples), handler1);
			
			ExempleDAO.creer(db);
			for(Exemple ex : exemples)
				ExempleDAO.ajouter(ex, db);

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.v(this.getClass().getSimpleName(), "Fin de la creation de la base.");
		Toast.makeText(this.context,
				context.getResources().getString(R.string.chargement_fin),
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		MotDAO.supprimer(db);
		onCreate(db);
	}
}
