package com.efounder.chat.handler;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.efounder.chat.activity.JFChatActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;

import org.json.JSONObject;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 监听聊天消息发送接收
 *
 * @author yqs
 */
public class ChatMessageListener implements JFMessageListener {
    private static final String TAG = "ChatMessageListener";

    private int id;
    private Context mContext;
    private Handler messageHandler;
    private int selfUserId;

    private static boolean showLogs = false;

    /**
     * 回话界面各种消息状态的监听
     *
     * @param mContext
     * @param id
     * @param messageHandler
     */
    public ChatMessageListener(Context mContext, int id, Handler messageHandler) {
        this.mContext = mContext;
        this.id = id;
        this.messageHandler = messageHandler;
        selfUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
    }

    @Override
    public synchronized void onReceive(final IMStruct002 imstruct002) {
        // XXX
        // 判断 如果不是系统消息（100代表系统消息）
        if (imstruct002.getMessageChildType() < 100) {
            //判断消息如果不是来自当前聊天的人，不发送回执
            switch (imstruct002.getToUserType()) {
                case StructFactory.TO_USER_TYPE_PERSONAL:
                    if (id == imstruct002.getFromUserId()) {
                        //发送已读回执
                        JFMessageManager.getInstance().sendReadMessage(imstruct002);
                        messageHandler.sendEmptyMessage(JFChatActivity.HANDLER_UPDATE_MSG_STATE);
                    }
                    break;
                case StructFactory.TO_USER_TYPE_GROUP:
                    if (id == imstruct002.getToUserId()) {
                        //彪为已读
                        JFMessageManager.getInstance().markedAsRead(imstruct002);
                        //	JFMessageManager.getInstance().sendReadMessage(imstruct002);
                        int sendMessageUserId = imstruct002.getFromUserId();//表示给你发消息的那个人，如张三李四
                        User currentUser = null;
                        currentUser = WeChatDBManager.getInstance().getOneFriendById(sendMessageUserId);
                        if (currentUser == null) {
                            currentUser = WeChatDBManager.getInstance().getOneUserById(sendMessageUserId);
                            if (currentUser == null) {
                                try {
                                    GetHttpUtil.getUserInfo(sendMessageUserId, mContext, new GetHttpUtil.GetUserListener() {
                                        @Override
                                        public void onGetUserSuccess(User user1) {
                                        }

                                        @Override
                                        public void onGetUserFail() {

                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        messageHandler.sendEmptyMessage(JFChatActivity.HANDLER_UPDATE_MSG_STATE);
                    }

                    break;
                case StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT:
                    //发送已读回执
                    JFMessageManager.getInstance().sendReadMessage(imstruct002);
                    messageHandler.sendEmptyMessage(JFChatActivity.HANDLER_UPDATE_MSG_STATE);
                    break;

                default:
                    break;
            }
            if (showLogs) {
                Log.i(TAG, "onReceive------消息状态：" + imstruct002.toString());
            }
        } else {
            //系统消息 我们处理一下是否正在输入的消息
            String messageString = imstruct002.getMessage();
            try {
                JSONObject jsonObject = new JSONObject(messageString);
                String CMD = jsonObject.optString("CMD", "");
                boolean isInputting = jsonObject.optInt("isInput", 0) == 1 ? true : false;
                //判断是正在输入消息并且消息是发给自己并且当前聊天人和消息发送人是同一人
                if ("inputting".equals(CMD) && selfUserId == imstruct002.getToUserId()
                        && imstruct002.getFromUserId() == id) {
                    if (System.currentTimeMillis() - imstruct002.getServerTime() > 30 * 1000) {
                        //当前时间和消息服务器时间对比，如果大于30s，表示之前的消息，就不处理了
                        return;
                    }
                    Message message = new Message();
                    message.what = JFChatActivity.HANDLER_SEND_INPUTTING_MSG;
                    message.obj = isInputting;
                    messageHandler.sendMessage(message);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onUpdate(int i, IMStruct002 imstruct002) {
        if (showLogs) {
            Log.i(TAG, "onUpdate------消息状态：" + imstruct002.toString());
        }
        messageHandler.sendEmptyMessage(JFChatActivity.HANDLER_UPDATE_MSG_STATE);
    }

    @Override
    public void onFailure(int i, IMStruct002 imstruct002) {
        if (showLogs) {
            Log.i(TAG, "onFailure------消息状态：" + imstruct002.toString());
        }
        messageHandler.sendEmptyMessage(JFChatActivity.HANDLER_UPDATE_MSG_STATE);
    }
}