package kimiko.coreen.app.data.base;

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 kimiko.coreen.app.R;
import kimiko.coreen.app.data.exemples.Exemple;
import kimiko.coreen.app.data.hanja.Hanja;
import kimiko.coreen.app.data.mots.Mot;
import kimiko.coreen.app.data.tools.ExempleLoader;
import kimiko.coreen.app.data.tools.HanjaLoader;
import kimiko.coreen.app.data.tools.MotLoader;

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

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
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();
		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);
				
			List<Hanja> hanjas = new ArrayList<Hanja>();
			DefaultHandler handler11 = new HanjaLoader(hanjas);
			parser.parse(context.getResources().openRawResource(R.raw.hanjas), handler11);
			
			HanjaDAO.creer(db);
			for(Hanja hanja : hanjas)
				HanjaDAO.ajouter(hanja, db);
			
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		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);
		HanjaDAO.supprimer(db);
		ExempleDAO.supprimer(db);
		onCreate(db);

	}
}
