/*
    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
/**
 * ContactProvider class.
 * @author dasilvj
 */
public class ContactProvider extends ContentProvider {

    private static final String TAG = "ContactProvider";

    private static HashMap<String, String> sContactsProjectionMap;

    private static final int CONTACTS = 1;
    private static final int CONTACT_ID = 2;

    private static final UriMatcher S_URI_MATCHER;
    static {
	S_URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
	S_URI_MATCHER.addURI(Beem.AUTHORITY, "contacts", CONTACTS);
	S_URI_MATCHER.addURI(Beem.AUTHORITY, "contacts/#", CONTACT_ID);

	sContactsProjectionMap = new HashMap<String, String>();
	sContactsProjectionMap.put(BaseColumns._ID, BaseColumns._ID);
	sContactsProjectionMap.put(Beem.Contacts.UID, Beem.Contacts.UID);
	sContactsProjectionMap.put(Beem.Contacts.JID, Beem.Contacts.JID);
	sContactsProjectionMap.put(Beem.Contacts.NICKNAME, Beem.Contacts.NICKNAME);
	sContactsProjectionMap.put(Beem.Contacts.ALIAS, Beem.Contacts.ALIAS);
	sContactsProjectionMap.put(Beem.Contacts.DATE_CREATED, Beem.Contacts.DATE_CREATED);
	sContactsProjectionMap.put(Beem.Contacts.DATE_MODIFIED, Beem.Contacts.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 CONTACTS:
		count = db.delete(Beem.CONTACTS_TABLE_NAME, selection, selectionArgs);
		break;

	    case CONTACT_ID:
		String contactId = uri.getPathSegments().get(1);
		count = db.delete(Beem.CONTACTS_TABLE_NAME, BaseColumns._ID + "=" + contactId
		    + (!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 CONTACTS:
		return Beem.Contacts.CONTENT_TYPE;

	    case CONTACT_ID:
		return Beem.Contacts.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) != CONTACTS) {
	    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.Contacts.UID)) {
	    // TODO :: Must check that the UID exists using UserProvider
	    throw new SQLException("No UID specified. Failed to insert row into " + uri);
	}

	if (!values.containsKey(Beem.Contacts.JID)) {
	    values.put(Beem.Contacts.JID, "");
	}

	if (!values.containsKey(Beem.Contacts.NICKNAME)) {
	    values.put(Beem.Contacts.JID, "");
	}

	if (!values.containsKey(Beem.Contacts.ALIAS)) {
	    values.put(Beem.Contacts.JID, "");
	}

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

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

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

	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.CONTACTS_TABLE_NAME, Beem.Contacts.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 CONTACTS:
		qb.setTables(Beem.CONTACTS_TABLE_NAME);
		qb.setProjectionMap(sContactsProjectionMap);
		break;

	    case CONTACT_ID:
		qb.setTables(Beem.USERS_TABLE_NAME);
		qb.setProjectionMap(sContactsProjectionMap);
		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.Contacts.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 CONTACTS:
		count = db.update(Beem.CONTACTS_TABLE_NAME, values, selection, selectionArgs);
		break;

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

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

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