/**
 * 
 */
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.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

/**
 * @author dasilvj
 *
 */
public class ContactProvider extends ContentProvider {

	private final static 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			sUriMatcher;
	private BeemDatabaseHelper				mOpenHelper;

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

		switch (sUriMatcher.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, Beem.Contacts._ID + "=" + contactId
					+ (!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 (sUriMatcher.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);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
        // Validate the requested uri
        if (sUriMatcher.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) == false) {
        	// 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) == false) {
            values.put(Beem.Contacts.JID, "");
        }
        
        if (values.containsKey(Beem.Contacts.NICKNAME) == false) {
            values.put(Beem.Contacts.JID, "");
        }
        
        if (values.containsKey(Beem.Contacts.ALIAS) == false) {
            values.put(Beem.Contacts.JID, "");
        }
        
        if (values.containsKey(Beem.Contacts.DATE_CREATED) == false) {
            values.put(Beem.Contacts.DATE_CREATED, now);
        }

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

        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(Beem.CONTACTS_TABLE_NAME, Beem.Contacts._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);
	}

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

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

		switch (sUriMatcher.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(Beem.Contacts._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;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        
        switch (sUriMatcher.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, Beem.Contacts._ID + "=" + contactId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
            break;

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

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

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

		sContactsProjectionMap = new HashMap<String, String>();
		sContactsProjectionMap.put(Beem.Contacts._ID, Beem.Contacts._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);
	}
}
