package com.eni.android.database;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class CapituloContentProvider extends ContentProvider {

	public static final Uri contentUri = Uri
			.parse("content://com.eni.android.database.CapituloContentProvider");
	private final String CONTENT_PROVIDER_MIME = "vnd.android.cursor.item/vnd.eni.android.database.provider.capitulos";

	private CapituloBaseSQLite dbHelper;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		long id = getId(uri);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			if (id < 0)
				return db.delete(CapituloBBDD.TABLA_CAPITULOS, selection,
						selectionArgs);
			else
				return db.delete(CapituloBBDD.TABLA_CAPITULOS,
						CapituloBBDD.COL_ID + "=" + id, selectionArgs);
		} finally {
			db.close();
		}
	}

	@Override
	public String getType(Uri uri) {
		return CONTENT_PROVIDER_MIME;
	}

	public long getId(Uri contentUri) {
		String lastPathSegment = contentUri.getLastPathSegment();
		if (lastPathSegment != null) {
			return Long.parseLong(lastPathSegment);
		}
		return -1;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			long id = db.insertOrThrow(CapituloBBDD.TABLA_CAPITULOS, null,
					values);

			if (id == -1) {
				throw new RuntimeException(String.format(
						"%s : Failed to insert [%s] for unknown reasons.",
						"AndroidProvider", values, uri));
			} else {
				return ContentUris.withAppendedId(uri, id);
			}

		} finally {
			db.close();
		}
	}

	@Override
	public boolean onCreate() {
		dbHelper = new CapituloBaseSQLite(getContext(), CapituloBBDD.NOMBRE_BBDD,
				null, CapituloBBDD.VERSION);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		long id = getId(uri);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		if (id < 0) {
			return db
					.query(CapituloBBDD.TABLA_CAPITULOS,
							projection, selection, selectionArgs, null, null,
							sortOrder);
		} else {
			return db.query(CapituloBBDD.TABLA_CAPITULOS,
					projection, CapituloBBDD.COL_ID + "=" + id, null, null, null,
					null);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		long id = getId(uri);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		try {
			if (id < 0)
				return db.update(CapituloBBDD.TABLA_CAPITULOS, values,
						selection, selectionArgs);
			else
				return db.update(CapituloBBDD.TABLA_CAPITULOS, values,
						CapituloBBDD.COL_ID + "=" + id, null);
		} finally {
			db.close();
		}
	}

}
