package com.rv.im.xmpp;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.rv.im.ImService;
import com.rv.im.call.JitsistateMachine;
import com.rv.im.call.event.MessageBusyEvent;
import com.rv.im.call.event.MessageEventSipEVent;
import com.rv.im.call.event.MessageHangUpPhone;
import com.rv.im.db.service.ChatMessageServiceImp;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.enums.CallTypeEnum;
import com.rv.im.enums.MessageTypeEnum;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jxmpp.jid.EntityBareJid;

/**
 * Created by Administrator on 2017/11/24.
 */

public class XChatMessageListener implements IncomingChatMessageListener {
    private ImService mService;

    public XChatMessageListener(ImService service) {
        mService = service;
    }

    @Override
    public void newIncomingMessage(EntityBareJid fromxx, Message message, Chat chat) {

        String packetID = message.getPacketID();
        String body = message.getBody();
        Log.e("xxxxxx",body) ;
        ChatMessage chatMessage = ChatMessage.json2Message(body);

        if (TextUtils.isEmpty(chatMessage.getPackId())) {
            chatMessage.setPackId(packetID);
        }

        int type = chatMessage.getMessageType();
        if (type == 0) { // 消息过滤
            return;
        }

        if (type == MessageTypeEnum.TEXT.getType() || type == MessageTypeEnum.PIC.getType()
                || type == MessageTypeEnum.FILE.getType() || type == MessageTypeEnum.VOICE.getType()) {
            ListenerManager.getInstance().notifyNewMesssage(chatMessage);
        } else if (type == MessageTypeEnum.VOLTE_CALL.getType()) { // 发送语音通话
            dealVolteCall(chatMessage);
        } else if (type == MessageTypeEnum.VIDEO_CALL.getType()) { // 发送视频通话
            dealVideoCall(chatMessage);
        }
    }

    /**********
     * 处理视频通话
     * @param chatMessage
     */
    private void dealVideoCall(ChatMessage chatMessage) {
        int callType = chatMessage.getCallType();
        if (callType == CallTypeEnum.CONNECT_VIDEO.getType()) {

            if (JitsistateMachine.isInCalling) {
                mService.sendBusyMessage(chatMessage.getMessageType(), chatMessage.getFromUserId());
                return;
            }
            if ((int) System.currentTimeMillis() / 1000 - chatMessage.getTimeSend() <= 30) {
                // 跳转到语音待接受界面
                EventBus.getDefault().post(new MessageEventSipEVent(callType, chatMessage.getFromUserId(), chatMessage));
            }
        } else if (callType == CallTypeEnum.CONNECTED_VIDEO.getType()) {
            EventBus.getDefault().post(new MessageEventSipEVent(callType, null, chatMessage));
        } else if (callType == CallTypeEnum.NO_CONNECT_VIDEO.getType()) {

            EventBus.getDefault().post(new MessageEventSipEVent(callType, null, chatMessage));
            String content;
            if (chatMessage.getTimeLen() == 0) {
                content = "对方取消视频通话";
            } else {
                content = "对方无人接听";
            }
            chatMessage.setContent(content);
            ChatMessageServiceImp.getInstance(mService.getApplicationContext()).addMessage(chatMessage);

            new Handler(Looper.getMainLooper()).postDelayed(() ->
                    EventBus.getDefault().post(new MessageHangUpPhone(chatMessage)), 1000);// 延迟一秒在发送挂断消息，防止当我们离线时，对方发起

        } else if (callType == CallTypeEnum.END_CONNECT_VIDEO.getType()) {

            ChatMessageServiceImp.getInstance(mService.getApplicationContext()).addMessage(chatMessage);
            EventBus.getDefault().post(new MessageHangUpPhone(chatMessage));
        }
    }

    /**********
     * 处理语音通话
     * @param chatMessage
     */
    private void dealVolteCall(ChatMessage chatMessage) {
        int callType = chatMessage.getCallType();
        if (callType == CallTypeEnum.CONNECT_VOICE.getType()) {
            ChatMessageServiceImp.getInstance(mService.getApplicationContext()).addMessage(chatMessage);
            if (JitsistateMachine.isInCalling) {  // 对方来电 ，本人 正在通话
                mService.sendBusyMessage(chatMessage.getMessageType(), chatMessage.getFromUserId());
                return;
            }
            if ((int) System.currentTimeMillis() / 1000 - chatMessage.getTimeSend() <= 30) {
                // 跳转到语音待接受界面
                EventBus.getDefault().post(new MessageEventSipEVent(callType, chatMessage.getFromUserId(), chatMessage));
            }
        } else if (callType == CallTypeEnum.CONNECTED_VOICE.getType()) {
            EventBus.getDefault().post(new MessageEventSipEVent(callType, null, chatMessage));
        } else if (callType == CallTypeEnum.NO_CONNECT_VOICE.getType()) {
            EventBus.getDefault().post(new MessageEventSipEVent(callType, null, chatMessage));
            ChatMessageServiceImp.getInstance(mService.getApplicationContext()).addMessage(chatMessage);

            new Handler(Looper.getMainLooper()).postDelayed(() ->
                    EventBus.getDefault().post(new MessageHangUpPhone(chatMessage)), 1000);// 延迟一秒在发送挂断消息，防止当我们离线时，对方发起通话之后又取消了通话，我们30秒内上线，在来点界面拉起时该Event也发送出去了
        } else if (callType == CallTypeEnum.END_CONNECT_VOICE.getType()) {
            // 通知通话界面挂断
            ChatMessageServiceImp.getInstance(mService.getApplicationContext()).addMessage(chatMessage);
            EventBus.getDefault().post(new MessageHangUpPhone(chatMessage));
        } else if (callType == CallTypeEnum.CALL_BUSY.getType()) {  // 忙线
            ChatMessageServiceImp.getInstance(mService.getApplicationContext()).addMessage(chatMessage);
            EventBus.getDefault().post(new MessageBusyEvent(chatMessage));
        }
    }
}
