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

package com.beem.project.beem.providers;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

/**
 * Provider to store messages send/receive.
 * @author marseille
 */
public class MessageProvider extends ContentProvider {

    private static final String TAG = "MessageProvider";
    private static final String DATABASE_NAME = "messages.db";
    private static final int DATABASE_VERSION = 1;
    private static final int MESSAGES = 1;
    private static final String MESSAGES_TABLE_NAME = "messages";
    private static final UriMatcher sUriMatcher;

    public static final String AUTHORITY = "com.beem.project.beem.providers.messageprovider";

    private static HashMap<String, String> messagesProjectionMap;
    private DatabaseHelper mDbHelper;

    /**
     * Constructor.
     */
    public MessageProvider() {
	Log.i(TAG, "Constructeur MessageProvider");
    }

    @Override
    public boolean onCreate() {
	Log.i(TAG, "On Create MessageProvider");
	mDbHelper = new DatabaseHelper(getContext());
	return true;

    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
	if (sUriMatcher.match(uri) != MESSAGES) {
	    throw new IllegalArgumentException("Unknown URI " + uri);
	}
	ContentValues values;
	if (initialValues != null)
	    values = new ContentValues(initialValues);
	else
	    values = new ContentValues();
	SQLiteDatabase db = null;
	db = mDbHelper.getWritableDatabase();
	long rowId = db.insert(MESSAGES_TABLE_NAME, Messages.BODY, values);
	if (rowId == -1)
	    throw new SQLException("Failed to insert row into " + uri);
	Uri messageUri = ContentUris.withAppendedId(Messages.CONTENT_URI, rowId);
	Log.e(TAG, "INSERT " + getContext());
	getContext().getContentResolver().notifyChange(messageUri, null);
	return messageUri;

    }

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

	switch (sUriMatcher.match(uri)) {
	    case MESSAGES:
		qb.setTables(MESSAGES_TABLE_NAME);
		qb.setProjectionMap(messagesProjectionMap);
		break;

	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}
	SQLiteDatabase db = mDbHelper.getReadableDatabase();
	Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
	c.setNotificationUri(getContext().getContentResolver(), uri);
	return c;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
	int count;
	SQLiteDatabase db = mDbHelper.getWritableDatabase();
	switch (sUriMatcher.match(uri)) {
	    case MESSAGES:
		count = db.update(MESSAGES_TABLE_NAME, values, selection, selectionArgs);
		break;

	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}
	getContext().getContentResolver().notifyChange(uri, null);
	return count;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
	int count;
	SQLiteDatabase db = mDbHelper.getWritableDatabase();
	switch (sUriMatcher.match(uri)) {
	    case MESSAGES:
		count = db.delete(MESSAGES_TABLE_NAME, 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 MESSAGES:
		return Messages.CONTENT_TYPE;
	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}
    }

    private class DatabaseHelper extends SQLiteOpenHelper {

	DatabaseHelper(Context context) {
	    super(context, DATABASE_NAME, null, DATABASE_VERSION);
	    Log.e(TAG, "ConStructeur");
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	    Log.e(TAG, "onCreate");
	    String createDatabase = "CREATE TABLE " + MESSAGES_TABLE_NAME + " (";
	    createDatabase += Messages._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";
	    createDatabase += Messages.FROM + " VARCHAR(255),";
	    createDatabase += Messages.MESSAGE_ID + " VARCHAR(255),";
	    createDatabase += Messages.TO + " VARCHAR(255),";
	    createDatabase += Messages.TYPE + " VARCHAR(255),";
	    createDatabase += Messages.SUBJECT + " VARCHAR(255),";
	    createDatabase += Messages.BODY + " LONGTEXT,";
	    createDatabase += Messages.THREAD + " VARCHAR(255),";
	    createDatabase += Messages.EXTRAS + " VARCHAR(255),";
	    createDatabase += Messages.IS_RECEIVE + " BOOLEAN,";
	    createDatabase += Messages.DATE_RECEIVE + " DATE,";
	    createDatabase += Messages.DATE_READ + " DATE";
	    createDatabase += ");";
	    try {
		db.execSQL(createDatabase);
	    } catch (SQLException e) {
		Log.e(TAG, "CREATE DB PROBLEM", e);
	    }
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	    Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
		+ ", which will destroy all old data");
	    db.execSQL("DROP TABLE IF EXISTS " + MESSAGES_TABLE_NAME);
	    onCreate(db);
	}
    }

    static {
	sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	sUriMatcher.addURI(AUTHORITY, MESSAGES_TABLE_NAME, MESSAGES);

	messagesProjectionMap = new HashMap<String, String>();
	messagesProjectionMap.put(Messages._ID, Messages._ID);
	messagesProjectionMap.put(Messages.FROM, Messages.FROM);
	messagesProjectionMap.put(Messages.MESSAGE_ID, Messages.MESSAGE_ID);
	messagesProjectionMap.put(Messages.TO, Messages.TO);
	messagesProjectionMap.put(Messages.TYPE, Messages.TYPE);
	messagesProjectionMap.put(Messages.SUBJECT, Messages.SUBJECT);
	messagesProjectionMap.put(Messages.BODY, Messages.BODY);
	messagesProjectionMap.put(Messages.THREAD, Messages.THREAD);
	messagesProjectionMap.put(Messages.EXTRAS, Messages.EXTRAS);
	messagesProjectionMap.put(Messages.IS_RECEIVE, Messages.IS_RECEIVE);
	messagesProjectionMap.put(Messages.DATE_RECEIVE, Messages.DATE_RECEIVE);
	messagesProjectionMap.put(Messages.DATE_READ, Messages.DATE_READ);
    }

}
