
package com.lianxin.pubqq.chat.adpter;

import java.util.Date;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.chat.chatrow.EMChatRow;
import com.lianxin.panqq.chat.chatrow.EMChatRowBigExpression;
import com.lianxin.panqq.chat.chatrow.EMChatRowCall;
import com.lianxin.panqq.chat.chatrow.EMChatRowCustom;
import com.lianxin.panqq.chat.chatrow.EMChatRowFile;
import com.lianxin.panqq.chat.chatrow.EMChatRowImage;
import com.lianxin.panqq.chat.chatrow.EMChatRowLocation;
import com.lianxin.panqq.chat.chatrow.EMChatRowText;
import com.lianxin.panqq.chat.chatrow.EMChatRowVideo;
import com.lianxin.panqq.chat.chatrow.EMChatRowVoice;
import com.lianxin.panqq.chat.chatrow.EMCustomChatRowProvider;
import com.lianxin.panqq.main.EMChatManager;
import com.lianxin.panqq.chat.EMConversation;
import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.chat.utils.DateUtils;
import com.lianxin.panqq.chat.widget.EMChatMessageList.MessageListItemClickListener;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class EMMessageAdapter extends BaseAdapter{

	private final static String TAG = "EMMessageAdapter";

	private Context context;
	
	private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;
	private static final int HANDLER_MESSAGE_SELECT_LAST = 1;
    private static final int HANDLER_MESSAGE_SEEK_TO = 2;

	private static final int MESSAGE_TYPE_RECV_TXT = 0;
	private static final int MESSAGE_TYPE_SENT_TXT = 1;
	private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
	private static final int MESSAGE_TYPE_SENT_LOCATION = 3;
	private static final int MESSAGE_TYPE_RECV_LOCATION = 4;
	private static final int MESSAGE_TYPE_RECV_IMAGE = 5;
	private static final int MESSAGE_TYPE_SENT_VOICE = 6;
	private static final int MESSAGE_TYPE_RECV_VOICE = 7;
	private static final int MESSAGE_TYPE_SENT_VIDEO = 8;
	private static final int MESSAGE_TYPE_RECV_VIDEO = 9;
	private static final int MESSAGE_TYPE_SENT_FILE = 10;
	private static final int MESSAGE_TYPE_RECV_FILE = 11;
	private static final int MESSAGE_TYPE_SENT_EXPRESSION = 12;
	private static final int MESSAGE_TYPE_RECV_EXPRESSION = 13;
	private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 14;
	private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 15;
	private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 16;
	private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 17;	
	private static final int MESSAGE_TYPE_SENT_CUSTOM = 18;
	private static final int MESSAGE_TYPE_RECV_CUSTOM = 19;
	
	public int itemTypeCount; 

	private EMConversation conversation;

    private String toChatUsername;
	private int toChatDestid;
	private int chatType;
	private int chatMode;
	
    private MessageListItemClickListener itemClickListener;
    private EMCustomChatRowProvider customRowProvider;
    
    private boolean showUserNick;
    private boolean showAvatar;
    private Drawable myBubbleBg;
    private Drawable otherBuddleBg;

    private ListView listView;

	public EMMessageAdapter(Context context, int destId, int chatType, ListView listView) {
		this.context = context;
		this.listView = listView;
        this.toChatDestid = destId;
        this.chatType = chatType;   
		if(chatType<5)
		    this.chatMode = 1;
		else
		    this.chatMode = 2;	       
		this.conversation = EMChatManager.getInstance().getornewConversation(toChatDestid,chatType);
	}

	public EMMessageAdapter(Context context, String username, int chatType, ListView listView) {
		this.context = context;
		this.listView = listView;
		toChatUsername = username;
	}	
	
	Handler handler = new Handler() {
		private void refreshList() {
			notifyDataSetChanged();
		}
		
		@Override
		public void handleMessage(android.os.Message message) {
			switch (message.what) {
			case HANDLER_MESSAGE_REFRESH_LIST:
				refreshList();
				break;
			case HANDLER_MESSAGE_SELECT_LAST:
               /* if (messages.length > 0) {
                    listView.setSelection(messages.length - 1);
                }*/
    			listView.setSelection(listView.getCount() - 1);                
                break;
            case HANDLER_MESSAGE_SEEK_TO:
                int position = message.arg1;
                listView.setSelection(position);
                break;
			default:
				break;
			}
		}
	};

	public void refresh() {
		if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
			return;
		}
		android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
		handler.sendMessage(msg);
	}
	
	/**
     * refresh and select the last
     */
    public void refreshSelectLast() {
        final int TIME_DELAY_REFRESH_SELECT_LAST = 100;
        handler.removeMessages(HANDLER_MESSAGE_REFRESH_LIST);
        handler.removeMessages(HANDLER_MESSAGE_SELECT_LAST);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_REFRESH_LIST, TIME_DELAY_REFRESH_SELECT_LAST);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SELECT_LAST, TIME_DELAY_REFRESH_SELECT_LAST);
    }
    
    /**
     * refresh and seek to the position
     */
    public void refreshSeekTo(int position) {
        handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
        android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_SEEK_TO);
        msg.arg1 = position;
        handler.sendMessage(msg);
    }
	

	public EMMessage getItem(int position) {
		/*if (messages != null && position < messages.length) {
			return messages[position];
		}
		return null;*/
		return conversation.getMessage(position);		
	}

	public long getItemId(int position) {
		return position;
	}
	
	/**
     * get count of messages
     */
    public int getCount() {
       // return messages == null ? 0 : messages.length;
		return conversation.getMsgCount();        
    }
	
	/**
	 * get number of message type, here 14 = (EMMessage.Type) * 2
	 */
	public int getViewTypeCount() {
	  /*  if(customRowProvider != null && customRowProvider.getCustomChatRowTypeCount() > 0){
	        return customRowProvider.getCustomChatRowTypeCount() + 14;
	    }*/
        return 21;
    }
	

	/**
	 * get type of item
	 */
	public int getItemViewType(int position) {
		EMMessage message = getItem(position); 
		if (message == null) {
			return -1;
		}
		
	/*	if(customRowProvider != null && customRowProvider.getCustomChatRowType(message) > 0){
		    return customRowProvider.getCustomChatRowType(message) + 13;
		}*/
		if(message.isCancel)
			return 20;		
		if (message.getMsgType() == EMMessage.MsgType.MSG_TEXT) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SENT_TXT;
		}
		if (message.getMsgType() == EMMessage.MsgType.MSG_DEFAULT) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SENT_TXT;
		}	
		if (message.getMsgType() == EMMessage.MsgType.MSG_IMAGE) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_IMAGE : MESSAGE_TYPE_SENT_IMAGE;
		}
		if (message.getMsgType() == EMMessage.MsgType.MSG_LOCATION) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_LOCATION : MESSAGE_TYPE_SENT_LOCATION;
		}
		if (message.getMsgType() == EMMessage.MsgType.MSG_VOICE) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE : MESSAGE_TYPE_SENT_VOICE;
		}
		if (message.getMsgType() == EMMessage.MsgType.MSG_VIDEO) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO : MESSAGE_TYPE_SENT_VIDEO;
		}
		if (message.getMsgType() == EMMessage.MsgType.MSG_FILE) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_FILE : MESSAGE_TYPE_SENT_FILE;
		}
		if (message.getMsgType() == EMMessage.MsgType.MSG_BIGFILE) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_FILE : MESSAGE_TYPE_SENT_FILE;
		}		
		if (message.getMsgType() == EMMessage.MsgType.MSG_EMOTION) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_EXPRESSION : MESSAGE_TYPE_SENT_EXPRESSION;
		}
		if (message.getMsgType() == EMMessage.MsgType.MSG_CUSTOM) {
			return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_CUSTOM : MESSAGE_TYPE_SENT_CUSTOM;
		}		
		if (message.getMsgType() == EMMessage.MsgType.MSG_CALL) {
			if (!message.isRead)
				return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL
						: MESSAGE_TYPE_SENT_VOICE_CALL;
			else 
				return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL
						: MESSAGE_TYPE_SENT_VIDEO_CALL;

		}	

		return -1;// invalid
	}
	
	protected EMChatRow createChatRow(Context context, EMMessage message, int position) {
        EMChatRow chatRow = null;
      /*  if(customRowProvider != null && customRowProvider.getCustomChatRow(message, position, this) != null){
            return customRowProvider.getCustomChatRow(message, position, this);
        }*/
		if(message.isCancel)
			return null; 			
	//		return inflater.inflate(R.layout.row_message_cancel, null) ;       
        switch (message.getMsgType()) {
        case EMMessage.MsgType.MSG_TEXT:
          //  if(message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)){
          //      chatRow = new EaseChatRowBigExpression(context, message, position, this);
          //  }else{
                chatRow = new EMChatRowText(context, message, position, this);
           // }
            break;
        case EMMessage.MsgType.MSG_LOCATION:
            chatRow = new EMChatRowLocation(context, message, position, this);
            break;
        case EMMessage.MsgType.MSG_FILE:
            chatRow = new EMChatRowFile(context, message, position, this);
            break;
        case EMMessage.MsgType.MSG_BIGFILE:
            chatRow = new EMChatRowFile(context, message, position, this);
            break;           
        case EMMessage.MsgType.MSG_IMAGE:
            chatRow = new EMChatRowImage(context, message, position, this);
            break;
        case EMMessage.MsgType.MSG_VOICE:
            chatRow = new EMChatRowVoice(context, message, position, this);
            break;
        case EMMessage.MsgType.MSG_VIDEO:
            chatRow = new EMChatRowVideo(context, message, position, this);
            break;
        case EMMessage.MsgType.MSG_CALL:
            chatRow = new EMChatRowCall(context, message, position, this);
            break;           
        case EMMessage.MsgType.MSG_EMOTION:
            chatRow = new EMChatRowBigExpression(context, message, position, this);
            break; 
        case EMMessage.MsgType.MSG_CUSTOM:
            chatRow = new EMChatRowCustom(context, message, position, this);
            break;           
        default:
            break;
        }

        return chatRow;
    }

	public View getView(final int position, View convertView, ViewGroup parent) {
		EMMessage message = getItem(position);
		if(message.isCancel){
			LayoutInflater inflater;
	        inflater = LayoutInflater.from(context);
			//return inflater.inflate(R.layout.row_message_cancel, null) ;
	        convertView = inflater.inflate(R.layout.row_message_cancel, null) ;	
	        TextView tv = (TextView) convertView.findViewById(R.id.tv_chatcontent);	 
	        int seid = message.getSendId();
	        //tv.setText("撤回一条消息");	
	        tv.setText(""+seid+"撤回一条消息");	        
			tv.setVisibility(View.VISIBLE);
			TextView timestamp = (TextView) convertView.findViewById(R.id.timestamp);			
			timestamp.setText(DateUtils.getTimestampString(new Date(message.getMsgTime()*1000)));
			timestamp.setVisibility(View.VISIBLE);	        
		}
		if(convertView == null){
			convertView = createChatRow(context, message, position);
		}

		if(!message.isCancel)
		((EMChatRow)convertView).setUpView(message, position, itemClickListener);
		
		return convertView;
	}


	public String getToChatUsername(){
	    return toChatUsername;
	}
	
	
	
	public void setShowUserNick(boolean showUserNick) {
        this.showUserNick = showUserNick;
    }


    public void setShowAvatar(boolean showAvatar) {
        this.showAvatar = showAvatar;
    }


    public void setMyBubbleBg(Drawable myBubbleBg) {
        this.myBubbleBg = myBubbleBg;
    }


    public void setOtherBuddleBg(Drawable otherBuddleBg) {
        this.otherBuddleBg = otherBuddleBg;
    }


    public void setItemClickListener(MessageListItemClickListener listener){
	    itemClickListener = listener;
	}
	
	public void setCustomChatRowProvider(EMCustomChatRowProvider rowProvider){
	    customRowProvider = rowProvider;
	}


    public boolean isShowUserNick() {
        return showUserNick;
    }


    public boolean isShowAvatar() {
        return showAvatar;
    }


    public Drawable getMyBubbleBg() {
        return myBubbleBg;
    }


    public Drawable getOtherBuddleBg() {
        return otherBuddleBg;
    }

}
