/*
    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 mucs.
 * @author marseille
 */
public class MUCsProvider extends ContentProvider {

    private static final String TAG = "MUCsProvider";
    private static final String DATABASE_NAME = "mucs.db";
    private static final int DATABASE_VERSION = 1;
    private static final int MUCS = 1;
    private static final String MUCS_TABLE_NAME = "mucs";
    private static final UriMatcher sUriMatcher;

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

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

    /**
     * Constructor.
     */
    public MUCsProvider() {
    }

    @Override
    public boolean onCreate() {
	mDbHelper = new DatabaseHelper(getContext());
	return true;

    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
	if (sUriMatcher.match(uri) != MUCS) {
	    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(MUCS_TABLE_NAME, null, values);
	if (rowId == -1)
	    throw new SQLException("Failed to insert row into " + uri);
	Uri mucUri = ContentUris.withAppendedId(MUCs.CONTENT_URI, rowId);
	getContext().getContentResolver().notifyChange(mucUri, null);
	return mucUri;

    }

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

	switch (sUriMatcher.match(uri)) {
	    case MUCS:
		qb.setTables(MUCS_TABLE_NAME);
		qb.setProjectionMap(mucsProjectionMap);
		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 MUCS:
		count = db.update(MUCS_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 MUCS:
		count = db.delete(MUCS_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 MUCS:
		return MUCs.CONTENT_TYPE;
	    default:
		throw new IllegalArgumentException("Unknown URI " + uri);
	}
    }

    private class DatabaseHelper extends SQLiteOpenHelper {

	DatabaseHelper(Context context) {
	    super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	    String createDatabase = "CREATE TABLE " + MUCS_TABLE_NAME + " (";
	    createDatabase += MUCs._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";
	    createDatabase += MUCs.NAME + " VARCHAR(255),";
	    createDatabase += MUCs.JID + " VARCHAR(255),";
	    createDatabase += MUCs.AUTO_JOIN + " BOOLEAN,";
	    createDatabase += MUCs.SHARED + " BOOLEAN,";
	    createDatabase += MUCs.NICKNAME + " VARCHAR(255),";
	    createDatabase += MUCs.PASSWORD + " VARCHAR(255),";
	    createDatabase += MUCs.ACCOUNT_NAME + " VARCHAR(255),";
	    createDatabase += MUCs.ACCOUNT_TYPE + " VARCHAR(255)";
	    createDatabase += ");";
	    try {
		db.execSQL(createDatabase);
	    } catch (SQLException e) {
		Log.e(TAG, "CREATE DB (MUC) 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 " + MUCS_TABLE_NAME);
	    onCreate(db);
	}
    }

    static {
	sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	sUriMatcher.addURI(AUTHORITY, MUCS_TABLE_NAME, MUCS);

	mucsProjectionMap = new HashMap<String, String>();
	mucsProjectionMap.put(MUCs._ID, MUCs._ID);
	mucsProjectionMap.put(MUCs.NAME, MUCs.NAME);
	mucsProjectionMap.put(MUCs.JID, MUCs.JID);
	mucsProjectionMap.put(MUCs.AUTO_JOIN, MUCs.AUTO_JOIN);
	mucsProjectionMap.put(MUCs.SHARED, MUCs.SHARED);
	mucsProjectionMap.put(MUCs.NICKNAME, MUCs.NICKNAME);
	mucsProjectionMap.put(MUCs.PASSWORD, MUCs.PASSWORD);
	mucsProjectionMap.put(MUCs.ACCOUNT_NAME, MUCs.ACCOUNT_NAME);
	mucsProjectionMap.put(MUCs.ACCOUNT_TYPE, MUCs.ACCOUNT_TYPE);
    }

}
