/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/

    Epitech, hereby disclaims all copyright interest in the program "Beem"
    written by Frederic-Charles Barthelery,
               Jean-Manuel Da Silva,
               Nikita Kozlov,
               Philippe Lago,
               Jean Baptiste Vergely,
               Vincent Veronis.

    Nicolas Sadirac, November 26, 2009
    President of Epitech.

    Flavien Astraud, November 26, 2009
    Head of the EIP Laboratory.

*/
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;

// TODO: Auto-generated Javadoc
/**
 * 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;

    /* (non-Javadoc)
     * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
     */
    @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;
    }

    /* (non-Javadoc)
     * @see android.content.ContentProvider#getType(android.net.Uri)
     */
    @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);
	}
    }

    /* (non-Javadoc)
     * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
     */
    @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);
    }

    /* (non-Javadoc)
     * @see android.content.ContentProvider#onCreate()
     */
    @Override
    public boolean onCreate() {
	mOpenHelper = new BeemDatabaseHelper(getContext(), TAG, Beem.USERS_TABLE_NAME, Beem.Users.QUERY_CREATE);
	return true;
    }

    /* (non-Javadoc)
     * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
     */
    @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;
    }

    /* (non-Javadoc)
     * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
     */
    @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;
    }
}
