package com.beem.project.beem.provider;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

/**
 * UserProvider class.
 * @author Jamu
 */
public class UserProvider extends ContentProvider {

    private static final String TAG = "UserProvider";

    private static HashMap<String, String> sUsersProjectionMap;

    private static final int USERS = 1;
    private static final int USER_ID = 2;

    private static final UriMatcher S_URI_MATCHER;
    static {
	S_URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
	S_URI_MATCHER.addURI(Beem.AUTHORITY, "users", USERS);
	S_URI_MATCHER.addURI(Beem.AUTHORITY, "users/#", USER_ID);

	sUsersProjectionMap = new HashMap<String, String>();
	sUsersProjectionMap.put(BaseColumns._ID, BaseColumns._ID);
	sUsersProjectionMap.put(Beem.Users.JUSERNAME, Beem.Users.JUSERNAME);
	sUsersProjectionMap.put(Beem.Users.DATE_CREATED, Beem.Users.DATE_CREATED);
	sUsersProjectionMap.put(Beem.Users.DATE_MODIFIED, Beem.Users.DATE_MODIFIED);
    }

    private BeemDatabaseHelper mOpenHelper;

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
	SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	int count;

	switch (S_URI_MATCHER.match(uri)) {
	    case USERS:
		count = db.delete(Beem.USERS_TABLE_NAME, selection, selectionArgs);
		break;

	    case USER_ID:
		String userID = uri.getPathSegments().get(1);
		count = db.delete(Beem.USERS_TABLE_NAME, BaseColumns._ID + "=" + userID
		    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
		break;

	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}

	getContext().getContentResolver().notifyChange(uri, null);
	return count;
    }

    @Override
    public String getType(Uri uri) {
	switch (S_URI_MATCHER.match(uri)) {
	    case USERS:
		return Beem.Users.CONTENT_TYPE;

	    case USER_ID:
		return Beem.Users.CONTENT_ITEM_TYPE;

	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
	// Validate the requested uri
	if (S_URI_MATCHER.match(uri) != USERS) {
	    throw new IllegalArgumentException("Unknown URI " + uri);
	}

	ContentValues values;
	if (initialValues != null) {
	    values = new ContentValues(initialValues);
	} else {
	    values = new ContentValues();
	}

	Long now = Long.valueOf(System.currentTimeMillis());

	// Make sure that the fields are all set
	if (!values.containsKey(Beem.Users.JUSERNAME)) {
	    throw new SQLException("No JUSERNAME specified. Failed to insert row into " + uri);
	}

	if (!values.containsKey(Beem.Users.DATE_CREATED)) {
	    values.put(Beem.Users.DATE_CREATED, now);
	}

	if (!values.containsKey(Beem.Users.DATE_MODIFIED)) {
	    values.put(Beem.Users.DATE_MODIFIED, now);
	}

	SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	long rowId = db.insert(Beem.USERS_TABLE_NAME, BaseColumns._ID, values);
	if (rowId > 0) {
	    Uri userUri = ContentUris.withAppendedId(Beem.Users.CONTENT_URI, rowId);
	    getContext().getContentResolver().notifyChange(userUri, null);
	    return userUri;
	}

	throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public boolean onCreate() {
	mOpenHelper = new BeemDatabaseHelper(getContext(), TAG, Beem.USERS_TABLE_NAME, Beem.Users.QUERY_CREATE);
	return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
	SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

	switch (S_URI_MATCHER.match(uri)) {
	    case USERS:
		qb.setTables(Beem.USERS_TABLE_NAME);
		qb.setProjectionMap(sUsersProjectionMap);
		break;

	    case USER_ID:
		qb.setTables(Beem.USERS_TABLE_NAME);
		qb.setProjectionMap(sUsersProjectionMap);
		qb.appendWhere(BaseColumns._ID + "=" + uri.getPathSegments().get(1));
		break;

	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}

	// If no sort order is specified use the default
	String orderBy;
	if (TextUtils.isEmpty(sortOrder)) {
	    orderBy = Beem.Users.DEFAULT_SORT_ORDER;
	} else {
	    orderBy = sortOrder;
	}

	// Get the database and run the query
	SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

	// Tell the cursor what uri to watch, so it knows when its source data
	// changes
	c.setNotificationUri(getContext().getContentResolver(), uri);
	return c;
    }

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

	switch (S_URI_MATCHER.match(uri)) {
	    case USERS:
		count = db.update(Beem.USERS_TABLE_NAME, values, selection, selectionArgs);
		break;

	    case USER_ID:
		String userId = uri.getPathSegments().get(1);
		count = db.update(Beem.USERS_TABLE_NAME, values, BaseColumns._ID + "=" + userId
		    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
		break;

	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}

	getContext().getContentResolver().notifyChange(uri, null);
	return count;
    }
}
