package com.eni.android.database;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ChapitreBDD {

	private static final int VERSION = 1;
	private static final String NOM_BDD = "chapitre.db";

	private static final String TABLE_CHAPITRES = "table_chapitres";
	private static final String COL_ID = "ID";
	private static final int NUM_COL_ID = 0;
	private static final String COL_NAME = "NAME";
	private static final int NUM_COL_NAME = 1;
	private static final String COL_DESC = "DESCRIPTION";
	private static final int NUM_COL_DESC = 2;

	private SQLiteDatabase bdd;

	private ChapitreBaseSQLite chapitres;

	public ChapitreBDD(Context context) {
		chapitres = new ChapitreBaseSQLite(context, NOM_BDD, null, VERSION);
	}

	public void openForWrite() {
			bdd = chapitres.getWritableDatabase();
	}

	public void openForRead() {
			bdd = chapitres.getReadableDatabase();
	}

	public void close() {
		bdd.close();
	}

	public SQLiteDatabase getBdd() {
		return bdd;
	}

	public long insertChapter(Chapitre chapitre) {
		ContentValues content = new ContentValues();
		content.put(COL_NAME, chapitre.getName());
		content.put(COL_DESC, chapitre.getDescription());
		return bdd.insert(TABLE_CHAPITRES, null, content);
	}

	public int updateChapter(int id, Chapitre chapitre) {
		ContentValues content = new ContentValues();
		content.put(COL_NAME, chapitre.getName());
		content.put(COL_DESC, chapitre.getDescription());
		return bdd.update(TABLE_CHAPITRES, content, COL_ID + " = " + id, null);
	}

	public int removeChapter(String name) {
		return bdd.delete(TABLE_CHAPITRES, COL_NAME + " = " + name, null);
	}

	public Chapitre getChapter(String name) {
		Cursor c = bdd.query(TABLE_CHAPITRES, new String[] { COL_ID, COL_NAME,
				COL_DESC }, COL_NAME + " LIKE \"" + name + "\"", null, null,
				null, COL_NAME);
		return cursorToChapter(c);
	}

	public Chapitre cursorToChapter(Cursor c) {
		if (c.getCount() == 0) {
			c.close();
			return null;
		}
		Chapitre chapter = new Chapitre();
		chapter.setId(c.getInt(NUM_COL_ID));
		chapter.setName(c.getString(NUM_COL_NAME));
		chapter.setDescription(c.getString(NUM_COL_DESC));
		c.close();
		return chapter;
	}

	public ArrayList<Chapitre> getAllChapters() {
		Cursor c = bdd.query(TABLE_CHAPITRES, new String[] { COL_ID, COL_NAME,
				COL_DESC }, null, null, null, null, COL_NAME);
		if (c.getCount() == 0) {
			c.close();
			return null;
		}
		ArrayList<Chapitre> chapterList = new ArrayList<Chapitre> ();
		while (c.moveToNext()) {
			Chapitre chapter = new Chapitre();
			chapter.setId(c.getInt(NUM_COL_ID));
			chapter.setName(c.getString(NUM_COL_NAME));
			chapter.setDescription(c.getString(NUM_COL_DESC));
			chapterList.add(chapter);
		}
		c.close();
		return chapterList;
	}

}
