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

import org.jivesoftware.smack.packet.Message;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.RawContacts;
import android.telephony.gsm.SmsMessage.MessageClass;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.beem.project.beem.BeemIntent;
import com.beem.project.beem.R;
import com.beem.project.beem.providers.Messages;

/**
 * The chat activity for communication with 1 contact.
 * @author Vincent V. <marseille@beem-project.com>
 */
public class Chat extends Activity implements OnKeyListener {

    private static final String TAG = "Chat";
    private String mjid;
    private String mAccount;

    /**
     * Constructor.
     */
    public Chat() {
	super();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    protected void onCreate(Bundle savedBundle) {
	super.onCreate(savedBundle);

	Uri contactURI = getIntent().getData();
	mjid = contactURI.getPathSegments().get(0);

	Cursor cursorAccount = getContentResolver().query(RawContacts.CONTENT_URI,
	    new String[] { RawContacts._ID, RawContacts.ACCOUNT_NAME }, RawContacts.SOURCE_ID + "=?", new String[] { mjid }, null);

	if (cursorAccount.getCount() == 1) {
	    cursorAccount.moveToFirst();
	    mAccount = cursorAccount.getString(cursorAccount.getColumnIndex(RawContacts.ACCOUNT_NAME));
	} else if (cursorAccount.getCount() > 1) {
	    // TODO : get account from jid. if multi account propose select
	}

	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
	boolean isCompact = settings.getBoolean("settings_chat_compact_key", false);
	// UI
	if (!isCompact) {
	    setNormalView();
	} else {
	    setContentView(R.layout.chat_compact);
	}

	Button sendButton = (Button) findViewById(R.id.chat_send_message);
	sendButton.setOnClickListener(new OnClickListener() {
	    @Override
	    public void onClick(View v) {
		sendMessage();
	    }
	});

    }

    private void setNormalView() {
	setContentView(R.layout.chat);
	TextView ContactNameTextView = (TextView) findViewById(R.id.chat_contact_name);
	ContactNameTextView.setText(mjid);
	TextView ContactStatusMsgTextView = (TextView) findViewById(R.id.chat_contact_status_msg);
	TextView ContactChatStateTextView = (TextView) findViewById(R.id.chat_contact_chat_state);
	ImageView ContactStatusIcon = (ImageView) findViewById(R.id.chat_contact_status_icon);
	LayerDrawable AvatarStatusDrawable = (LayerDrawable) ContactStatusIcon.getDrawable();
	AvatarStatusDrawable.setLayerInset(1, 36, 36, 0, 0);

	final Cursor cursorMessage = getContentResolver().query(Messages.CONTENT_URI,
	    new String[] { Messages._ID, Messages.TO, Messages.FROM, Messages.DATE_READ, Messages.BODY },
	    Messages.TO + "=? OR " + Messages.FROM + " like '%" + mjid + "%'", new String[] { mjid }, null);

	BeemMessageList mAdapterMessageList = new BeemMessageList(this, R.layout.chat_msg_row, cursorMessage,
	    new String[] { Messages._ID, Messages.TO, Messages.FROM, Messages.DATE_READ, Messages.BODY }, new int[] {
		R.id.chatmessagename, R.id.chatmessagedate, R.id.chatmessagetext });

	ListView listView = (ListView) findViewById(R.id.chat_messages);
	registerForContextMenu(listView);
	listView.setAdapter(mAdapterMessageList);

    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
	Log.e(TAG, "ONKEY");
	if (event.getAction() == KeyEvent.ACTION_DOWN) {
	    Log.e(TAG, "ONKEY");
	    switch (keyCode) {
		case KeyEvent.KEYCODE_ENTER:
		    sendMessage();
		    return true;
		default:
		    return false;
	    }
	}
	return false;
    }

    private void sendMessage() {
	EditText inputField = (EditText) findViewById(R.id.chat_input);
	final String inputContent = inputField.getText().toString();
	
	Intent intent = new Intent(BeemIntent.ACTION_SEND_MESSAGE);
	intent.putExtra(BeemIntent.EXTRA_ACCOUNT, mAccount);
	intent.putExtra(BeemIntent.EXTRA_JID, mjid);
	intent.putExtra(BeemIntent.EXTRA_MESSAGE, inputContent);
	startService(intent);

	inputField.setText(null);
    }

    /**
     * Adapter message list.
     */
    private static class BeemMessageList extends SimpleCursorAdapter implements Filterable {

	private Context mContext;
	private int mLayout;

	public BeemMessageList(Context context, int layout, Cursor c, String[] from, int[] to) {
	    super(context, layout, c, from, to);
	    mContext = context;
	    mLayout = layout;
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
	    final LayoutInflater inflater = LayoutInflater.from(mContext);
	    return inflater.inflate(mLayout, parent, false);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
	    String jid = cursor.getString(cursor.getColumnIndex(Messages.TO));
	    if (jid.length() == 0)
		jid = cursor.getString(cursor.getColumnIndex(Messages.FROM));
	    String date = cursor.getString(cursor.getColumnIndex(Messages.DATE_READ));
	    String body = cursor.getString(cursor.getColumnIndex(Messages.BODY));
	    TextView nameText = (TextView) view.findViewById(R.id.chatmessagename);
	    if (nameText != null) {
		nameText.setText(jid);
	    }

	    TextView dateText = (TextView) view.findViewById(R.id.chatmessagedate);
	    if (dateText != null) {
		dateText.setText(date);
	    }

	    TextView bodyText = (TextView) view.findViewById(R.id.chatmessagetext);
	    if (bodyText != null) {
		bodyText.setText(body);
	    }

	}

    }
}
