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 CapituloBBDD
{
	public static final int VERSION = 1;
	public static final String NOMBRE_BBDD = "capitulo.db";

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

	private SQLiteDatabase bdd;

	private CapituloBaseSQLite chapitres;

	public CapituloBBDD(Context context) {
		chapitres = new CapituloBaseSQLite(context, NOMBRE_BBDD, 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(Capitulo capitulo) {
		ContentValues content = new ContentValues();
		content.put(COL_NAME, capitulo.getName());
		content.put(COL_DESC, capitulo.getDescription());
		return bdd.insert(TABLA_CAPITULOS, null, content);
	}

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

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

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

	public Capitulo cursorToChapter(Cursor c) {
		if (c.getCount() == 0) {
			c.close();
			return null;
		}
		Capitulo chapter = new Capitulo();
		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<Capitulo> getAllChapters() {
		Cursor c = bdd.query(TABLA_CAPITULOS, new String[] { COL_ID, COL_NAME,
				COL_DESC }, null, null, null, null, COL_NAME);
		if (c.getCount() == 0) {
			c.close();
			return null;
		}
		ArrayList<Capitulo> chapterList = new ArrayList<Capitulo> ();
		while (c.moveToNext()) {
			Capitulo chapter = new Capitulo();
			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;
	}
}
