package com.sjyt.icom.asst.context.handle.msgtype.req;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sjyt.icom.asst.common.enums.ErrorCodeEnum;
import com.sjyt.icom.asst.common.enums.MsgTypeEnum;
import com.sjyt.icom.asst.common.model.message.Message;
import com.sjyt.icom.asst.common.model.message.NewsLetter;
import com.sjyt.icom.asst.common.model.sdp.FutureAnswer;
import com.sjyt.icom.asst.common.model.sdp.RespError;
import com.sjyt.icom.asst.common.util.FuncUtils;
import com.sjyt.icom.asst.service.impl.RoomManageService;
import com.sjyt.icom.asst.service.impl.SendMsgService;
import com.sjyt.icom.asst.service.impl.SrsRpcService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * <p>一对一音视频通话（发起者）</p>
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/6/22 14:43
 */
@Component
@AllArgsConstructor
public class SponsorOne2OneAvMsgHandle extends AvMsgHandle {
    private final RoomManageService roomManage;
    private final SrsRpcService srsRpcService;
    private final SendMsgService sendMsg;

    /**
     * 执行链
     *
     * @param event t
     */
    @Override
    public void doChain(AvMsgHandleEvent event) {
        NewsLetter newsLetter = event.getNewsLetter();
        Map<String, Object> body = newsLetter.getMessage().getBody();
        String msgCode = (String) body.get(MsgTypeEnum.META);
        if (ObjectUtil.isNotEmpty(body) && ObjectUtil.equal(msgCode, MsgTypeEnum.ReqSponsor.getCode())) {
            //判断对方状态是否占线
            FuncUtils.isTrueOrFalse(roomManage.isBusy(newsLetter.getTo())).trueOrFalseHandle(() -> {
                CompletableFuture<FutureAnswer> completableFuture = srsRpcService.sdp(newsLetter);
                completableFuture.thenAcceptAsync(it -> {
                    Message message = it.getNewsLetter().getMessage();
                    FuncUtils.isTrueOrFalse(it.getCode() == 0)
                            .trueOrFalseHandle(() -> {
                                message.setBody(BeanUtil.beanToMap(it.getRespAnswer()));
                                //推送
                            }, () -> {
                                RespError error = sendMsg.getError(ErrorCodeEnum.UNKNOWN_SDP_ERROR);
                                message.setBody(BeanUtil.beanToMap(error));
                            });
                    sendMsg.send2From(it.getNewsLetter());
                });
            }, () -> {//对方占线
                sendMsg.sendForError(newsLetter.getFrom(), ErrorCodeEnum.UNKNOWN_ERROR);
            });
        } else {
           // publisher.publish(event);
            doChain(event);
        }
    }
}
