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 ChapitreContentProvider extends ContentProvider {

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

	private ChapitreBaseSQLite 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(ChapitreBDD.TABLE_CHAPITRES, selection,
						selectionArgs);
			else
				return db.delete(ChapitreBDD.TABLE_CHAPITRES,
						ChapitreBDD.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(ChapitreBDD.TABLE_CHAPITRES, null,
					values);

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

		} finally {
			db.close();
		}
	}

	@Override
	public boolean onCreate() {
		dbHelper = new ChapitreBaseSQLite(getContext(), ChapitreBDD.NOM_BDD,
				null, ChapitreBDD.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(ChapitreBDD.TABLE_CHAPITRES,
							projection, selection, selectionArgs, null, null,
							sortOrder);
		} else {
			return db.query(ChapitreBDD.TABLE_CHAPITRES,
					projection, ChapitreBDD.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(ChapitreBDD.TABLE_CHAPITRES, values,
						selection, selectionArgs);
			else
				return db.update(ChapitreBDD.TABLE_CHAPITRES, values,
						ChapitreBDD.COL_ID + "=" + id, null);
		} finally {
			db.close();
		}
	}

}
