package com.rong.io.live.helper;

import android.text.TextUtils;
import android.util.Log;

import com.rong.io.live.bean.User;
import com.rong.io.live.callback.ClickCallback;
import com.rong.io.live.callback.IRoomCallBack;
import com.rong.io.live.constant.CurrentStatusType;
import com.rong.io.live.listener.RCLiveEventListener;
import com.rong.io.live.manager.MusicControl;
import com.rong.io.live.manager.RCChatRoomMessageManager;
import com.rong.io.live.message.RCChatJoinRoomMessage;
import com.rong.io.live.message.RCChatModeMessage;
import com.rong.io.live.message.RCChatroomLocationMessage;
import com.rong.io.live.message.RCUserAddLikeMessage;
import com.rong.io.live.message.RCUserSeatApplyMessage;
import com.rong.io.live.message.RCUserSeatResponseMessage;
import com.rong.io.live.message.RCUserSeatsCtrlMessage;
import com.rong.io.live.model.RCLivevideoFinishReason;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.rongcloud.rtc.api.RCRTCConfig;
import cn.rongcloud.rtc.api.RCRTCEngine;
import cn.rongcloud.rtc.api.RCRTCRoom;
import cn.rongcloud.rtc.api.RCRTCRoomConfig;
import cn.rongcloud.rtc.api.callback.IRCRTCResultCallback;
import cn.rongcloud.rtc.api.callback.IRCRTCResultDataCallback;
import cn.rongcloud.rtc.base.RCRTCLiveRole;
import cn.rongcloud.rtc.base.RCRTCRoomType;
import cn.rongcloud.rtc.base.RCRTCVideoFrame;
import cn.rongcloud.rtc.base.RTCErrorCode;
import io.rong.imkit.IMCenter;
import io.rong.imlib.IRongCoreCallback;
import io.rong.imlib.IRongCoreEnum;
import io.rong.imlib.MessageTag;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.chatroom.base.RongChatRoomClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.TextMessage;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;

/**
 * Author by pq, Date on 2022/3/29.
 */
public class LiveEventHelper extends RongIMClient.OnReceiveMessageWrapperListener implements ILiveEventHelper, RCLiveEventListener {
    private String roomId;//roomId
    private String createUserId;//房间创建人ID
    private RCRTCRoom rtcRoom;
    private List<MessageContent> messageList = new ArrayList<>();

    @Override
    public void onRoomInfoReady() {

    }

    @Override
    public void onRoomInfoUpdate(String key, String value) {

    }

    @Override
    public void onUserEnter(String userId, int onlineCount) {

    }

    @Override
    public void onUserExit(String userId, int onlineCount) {

    }

    @Override
    public void onUserKickOut(String userId, String operatorId) {

    }

    @Override
    public void onLiveVideoUpdate(List<String> lineMicUserIds) {

    }

    @Override
    public void onLiveVideoStarted() {

    }

    @Override
    public void onLiveVideoStopped(RCLivevideoFinishReason reason) {

    }

    @Override
    public void onReceiveMessage(Message message) {

    }

    @Override
    public void onNetworkStatus(long delayMs) {

    }

    @Override
    public void onOutputSampleBuffer(RCRTCVideoFrame frame) {

    }

    @Override
    public RCRTCConfig.Builder onInitRCRTCConfig(RCRTCConfig.Builder builder) {
        return null;
    }

    @Override
    public void onRoomMixTypeChange() {

    }

    @Override
    public void onRoomDestroy() {

    }



    @Override
    public boolean onReceived(Message message, int left, boolean hasPackage, boolean offline) {
        if (message == null) {
            return false;
        }
        Log.i("pq", "onReceived message" + message);
        if (!TextUtils.isEmpty(roomId) && TextUtils.equals(message.getTargetId(), roomId) && message.getConversationType() == Conversation.ConversationType.CHATROOM) {
            //统一处理
            RCChatRoomMessageManager.onReceiveMessage(roomId, message);
            return true;
        }
        return false;
    }


    private static class helper {
        static final LiveEventHelper INSTANCE = new LiveEventHelper();
    }

    public static LiveEventHelper getInstance() {
        return helper.INSTANCE;
    }

    @Override
    public void register(String roomId) {
        IMCenter.getInstance().removeOnReceiveMessageListener(this);
        IMCenter.getInstance().addOnReceiveMessageListener(this);
        this.roomId = roomId;
    }

    private void releaseLiveRoom() {
        if (messageList != null) {
            messageList.clear();
        }
        //移除直播间事件监听
        if (rtcRoom != null) {
            rtcRoom.unregisterRoomListener();
            this.rtcRoom = null;
        }
    }

    @Override
    public void unRegister() {
        this.roomId = "";
        this.createUserId = "";
        releaseLiveRoom();
        quitChatRoom();
        //移除聊天消息监听
        IMCenter.getInstance().removeOnReceiveMessageListener(this);
        leaveRoom(null);
    }

    /**
     * 发送消息
     *
     * @param messageContent 消息体
     * @param isShowLocation 是否在本地显示
     */
    @Override
    public void sendMessage(MessageContent messageContent, boolean isShowLocation) {
        if (!TextUtils.isEmpty(roomId)) {
            if (messageContent instanceof RCChatroomLocationMessage) {
                Message locationMsg = Message.obtain(roomId, Conversation.ConversationType.CHATROOM, messageContent);
                MessageTag annotation = messageContent.getClass().getAnnotation(MessageTag.class);
                if (annotation != null) {
                    locationMsg.setObjectName(annotation.value());
                }
                RCChatRoomMessageManager.sendLocationMessage(roomId, locationMsg);
                if (isShowingMessage(messageContent)) {
                    messageList.add(messageContent);
                }
            } else {
                RCChatRoomMessageManager.sendChatMessage(roomId, messageContent, isShowLocation
                        , new Function1<Integer, Unit>() {
                            @Override
                            public Unit invoke(Integer integer) {
                                Log.i("pq", "发送成功");
                                if (isShowLocation) {
                                    messageList.add(messageContent);
                                }
                                return null;
                            }
                        }, new Function2<RongIMClient.ErrorCode, Integer, Unit>() {
                            @Override
                            public Unit invoke(RongIMClient.ErrorCode coreErrorCode, Integer integer) {
                                Log.i("pq", "发送失败:" + coreErrorCode + "---" + integer);
                                return null;
                            }
                        });
            }
        } else {
            Log.i("pq", "房间信息错误roomid为null");
        }
    }

    @Override
    public CurrentStatusType getCurrentStatus() {
        return null;
    }

    @Override
    public void setCurrentStatus(CurrentStatusType currentStatus) {

    }

    @Override
    public void leaveRoom(IRoomCallBack callback) {
        RCRTCEngine.getInstance().leaveRoom(new IRCRTCResultCallback() {
            @Override
            public void onSuccess() {
                MusicControl.getInstance().stopPlayMusic();
                releaseLiveRoom();
                if (callback != null)
                    callback.onSuccess();
            }

            @Override
            public void onFailed(RTCErrorCode rtcErrorCode) {
                if (callback != null) {
                    callback.onError(rtcErrorCode.getValue(), rtcErrorCode.getReason());
                }
            }

        });
    }

    public void joinChatRoom(String chatroomId, final IRongCoreCallback.OperationCallback callback) {
        roomId = chatroomId;
        if (TextUtils.isEmpty(roomId)) {
            return;
        }
        RongChatRoomClient.getInstance().quitChatRoom(roomId, new IRongCoreCallback.OperationCallback() {
            @Override
            public void onSuccess() {
                Log.i("pq", "quit chart room success");
                joinChatRoomAfterLeave(chatroomId, callback);
            }

            @Override
            public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
                Log.i("pq", "quit chart room fail:" + coreErrorCode);
                joinChatRoomAfterLeave(chatroomId, callback);
            }
        });
    }

    private void joinChatRoomAfterLeave(String chatroomId, final IRongCoreCallback.OperationCallback callback) {
        //defMessageCount 拉取聊天消息记录数.
        //1. -1 表示不获取任何历史消息;
        //2. 0 表示使用 sdk 默认的设置（默认为10 条）;
        //3. 获取的消息数量 最大值为 50 条
        RongChatRoomClient.getInstance().joinChatRoom(chatroomId, -1, callback);
    }

    public void quitChatRoom() {
        if (TextUtils.isEmpty(roomId)) {
            return;
        }
        RongChatRoomClient.getInstance().quitChatRoom(roomId, new IRongCoreCallback.OperationCallback() {
            @Override
            public void onSuccess() {
                Log.i("pq", "quit chart room success");
            }

            @Override
            public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
                Log.i("pq", "quit chart room fail:" + coreErrorCode);
            }
        });
    }

    @Override
    public void joinRoom(String roomId,RCRTCLiveRole role, ClickCallback<Boolean> callback) {
        RongIMClient.ConnectionStatusListener.ConnectionStatus currentConnectionStatus = RongIMClient.getInstance().getCurrentConnectionStatus();
        if (currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
            //im连接状态
            RCRTCRoomConfig roomConfig = RCRTCRoomConfig.Builder.create()
                    // 根据实际场景，选择音视频直播：LIVE_AUDIO_VIDEO 或音频直播：LIVE_AUDIO
                    .setRoomType(RCRTCRoomType.LIVE_AUDIO_VIDEO)
                    .setLiveRole(role)
                    .build();
            RCRTCEngine.getInstance().joinRoom(roomId, roomConfig, new IRCRTCResultDataCallback<RCRTCRoom>() {
                @Override
                public void onSuccess(final RCRTCRoom room) {
                    // 保存房间对象
                    LiveEventHelper.this.rtcRoom = room;
                    callback.onResult(true, "");
                }

                @Override
                public void onFailed(RTCErrorCode code) {
                    callback.onResult(false, "join room error,errorCode:" + code);
                }
            });
        } else {
            Log.i("pq", "rongIM unConnection");
//            callback.onResult(false, "rongIM unConnection");
        }
    }

    @Override
    public void pickUserToSeat(String userId, int index, ClickCallback<Boolean> callback) {

    }

    @Override
    public void cancelInvitation(String userId, ClickCallback<Boolean> callback) {

    }

    @Override
    public void acceptRequestSeat(String userId, ClickCallback<Boolean> callback) {

    }

    @Override
    public void rejectRequestSeat(String userId, ClickCallback<Boolean> callback) {

    }

    @Override
    public void cancelRequestSeat(ClickCallback<Boolean> callback) {

    }

    @Override
    public void lockSeat(int index, boolean isClose, ClickCallback<Boolean> callback) {

    }

    @Override
    public void switchToSeat(int seatIndex, ClickCallback<Boolean> callback) {

    }

    @Override
    public void muteSeat(int index, boolean isMute, ClickCallback<Boolean> callback) {

    }

    @Override
    public void switchVideoOrAudio(int index, boolean isVideo, ClickCallback<Boolean> callback) {

    }

    @Override
    public void MuteSelf(int index, boolean isMute, ClickCallback<Boolean> callback) {

    }

    @Override
    public void kickUserFromRoom(User user, ClickCallback<Boolean> callback) {

    }

    @Override
    public void kickUserFromSeat(User user, ClickCallback<Boolean> callback) {

    }

    @Override
    public void changeUserRoom(String roomId) {

    }

    @Override
    public void finishRoom(ClickCallback<Boolean> callback) {

    }

    @Override
    public void begin(String roomId, ClickCallback<Boolean> callback) {
    }

    @Override
    public void prepare(ClickCallback<Boolean> callback) {

    }

    @Override
    public void requestLiveVideo(int index, ClickCallback<Boolean> callback) {

    }

    @Override
    public void enterSeat(int index, ClickCallback<Boolean> callback) {

    }

    @Override
    public void leaveSeat(ClickCallback<Boolean> callback) {

    }

    @Override
    public void updateRoomInfoKv(String key, String vaule, ClickCallback<Boolean> callback) {

    }

    @Override
    public void getRoomInfoByKey(String key, ClickCallback<Boolean> callback) {

    }

    @Override
    public void getRoomInfoByKey(List<String> keys, ClickCallback<Map<String, String>> callback) {

    }

    @Override
    public void getRequestLiveVideoIds(ClickCallback<List<String>> callback) {

    }

    public String getRoomId() {
        return roomId;
    }

    /**
     * 获取当前直播视频房间
     *
     * @return
     */
    public RCRTCRoom getRtcRoom() {
        return rtcRoom;
    }

    public void setCreateUserId(String createUserId) {
        this.createUserId = createUserId;
    }

    /**
     * 是否显示在直播间消息列表中的消息
     *
     * @param content
     * @return
     */
    public boolean isShowingMessage(MessageContent content) {
        if (content instanceof TextMessage || content instanceof RCChatJoinRoomMessage
                || content instanceof RCChatroomLocationMessage || content instanceof RCUserSeatsCtrlMessage || content instanceof RCChatModeMessage
                || content instanceof RCUserSeatApplyMessage || content instanceof RCUserSeatResponseMessage) {
            return true;
        }
        return false;
    }

    public List<MessageContent> getMessageList() {
        return messageList;
    }
}
