package com.rv.im.call;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.rv.im.Constants;
import com.rv.im.ImSetting;
import com.rv.im.call.event.MessageEventCancelOrHangUp;
import com.rv.im.call.event.MessageEventSipEVent;
import com.rv.im.call.event.MessageEventSipPreview;
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.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.UUID;

/**
 * Audio Video Call Meet Controller
 */
public class AudioOrVideoController {
    private static AudioOrVideoController instance;
    private Context mContext;
    private LogoutListener mListener;

    private AudioOrVideoController(Context context, LogoutListener listener) {
        this.mContext = context;
        this.mListener = listener;
        EventBus.getDefault().register(this);
    }

    public static AudioOrVideoController init(Context context, LogoutListener listener) {
        if (instance == null) {
            instance = new AudioOrVideoController(context, listener);
        }
        return instance;
    }

    // 单聊 通话 来电
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(final MessageEventSipEVent messsage) {
        if (messsage.number == CallTypeEnum.CONNECT_VOICE.getType() || messsage.number == CallTypeEnum.CONNECT_VIDEO.getType()) {
            if (!JitsistateMachine.isInCalling) {
                Intent intent = new Intent(mContext, JitsiIncomingcall.class);
                if (messsage.number == CallTypeEnum.CONNECT_VOICE.getType()) {
                    intent.putExtra(CallConstants.AUDIO_OR_VIDEO_OR_MEET, CallConstants.Audio);
                } else {
                    intent.putExtra(CallConstants.AUDIO_OR_VIDEO_OR_MEET, CallConstants.Video);
                }
                intent.putExtra("fromuserid", messsage.touserid);
                intent.putExtra("touserid", messsage.touserid);
                intent.putExtra("name", messsage.message.getFromUserName());
                if (!TextUtils.isEmpty(messsage.message.getFilePath())) {
                    intent.putExtra("meetUrl", messsage.message.getFilePath());
                }
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        } else if (messsage.number == CallTypeEnum.NO_CONNECT_VOICE.getType() || messsage.number == CallTypeEnum.NO_CONNECT_VIDEO.getType()) {
            if (messsage.message.getTimeLen() == 0) {
                EventBus.getDefault().post(new MessageHangUpPhone(messsage.message));
            }
        } else if (messsage.number == CallTypeEnum.CONNECTED_VOICE.getType()
                || messsage.number == CallTypeEnum.CONNECTED_VIDEO.getType()) {
            EventBus.getDefault().post(new MessageEventSipPreview(messsage.number == CallTypeEnum.CONNECTED_VOICE.getType()));
        }
    }

    /**
     * 我方取消、挂断通话后发送XMPP消息给对方
     * copy by AudioOrVideoController
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(final MessageEventCancelOrHangUp event) {
        String mLoginUserId = ImSetting.getUserId();
        ChatMessage message = new ChatMessage();

        if (event.type == CallTypeEnum.NO_CONNECT_VOICE.getType()) {          // 取消 语音通话
            message.setMessageType(MessageTypeEnum.VOLTE_CALL);
            message.setCallType(CallTypeEnum.NO_CONNECT_VOICE);
        } else if (event.type == CallTypeEnum.END_CONNECT_VOICE.getType()) {// 取消 视频通话
            message.setMessageType(MessageTypeEnum.VOLTE_CALL);
            message.setCallType(CallTypeEnum.END_CONNECT_VOICE);
        } else if (event.type == CallTypeEnum.NO_CONNECT_VIDEO.getType()) {// 挂断 语音通话
            message.setMessageType(MessageTypeEnum.VIDEO_CALL);
            message.setCallType(CallTypeEnum.NO_CONNECT_VIDEO);
        } else if (event.type == CallTypeEnum.END_CONNECT_VIDEO.getType()) {// 挂断 视频通话
            message.setMessageType(MessageTypeEnum.VIDEO_CALL);
            message.setCallType(CallTypeEnum.END_CONNECT_VIDEO);
        }
        message.setFromUserId(mLoginUserId);
        message.setFromUserName(ImSetting.getUserName());
        message.setToUserId(event.toUserId);
        message.setContent(event.content);
        message.setTimeLen(event.callTimeLen);
        message.setTimeSend(System.currentTimeMillis());
        message.setPackId(UUID.randomUUID().toString().replaceAll("-", ""));
        ChatMessageServiceImp.getInstance(ImSetting.getContext()).addMessage(message);
        sendMsgBroad(event.toUserId, message);
    }

    public void sendMsgBroad(String call_toUser, ChatMessage message) {
        Intent intent = new Intent();
        intent.setAction(Constants.ACTIONS.ACTION_SEND_RECEIVER);
        intent.setPackage(ImSetting.getContext().getPackageName());
        intent.putExtra(Constants.KEYS.KEY_MESSAGE_TARGET, call_toUser);
        intent.putExtra(Constants.KEYS.KEY_MESSAGE_CONTENT, message.toJsonString());
        ImSetting.getContext().sendBroadcast(intent);
    }

    public void release() {
        EventBus.getDefault().unregister(this);
    }


    public interface LogoutListener {
        void logout();
    }
}
