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.News;
import com.sjyt.icom.asst.common.model.message.NewsHelper;
import com.sjyt.icom.asst.common.model.room.AbsRoom;
import com.sjyt.icom.asst.common.model.room.IcomClient;
import com.sjyt.icom.asst.common.model.sdp.FutureAnswer;
import com.sjyt.icom.asst.common.model.sdp.ReqOffer;
import com.sjyt.icom.asst.common.model.sdp.RespBusy;
import com.sjyt.icom.asst.common.model.sdp.RespError;
import com.sjyt.icom.asst.common.util.FuncUtils;
import com.sjyt.icom.asst.common.util.JsonUtils;
import com.sjyt.icom.asst.service.impl.RoomManageService;
import com.sjyt.icom.asst.service.impl.SrsRpcOfferDTO;
import com.sjyt.icom.asst.service.impl.SrsRpcService;
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
public class SponsorOne2OneAvMsgHandle extends AvMsgHandle {
    public SponsorOne2OneAvMsgHandle(RoomManageService roomManage, SrsRpcService srsRpcService) {
        super(roomManage, srsRpcService);
    }

    /**
     * 执行链
     *
     * @param event t
     */
    @Override
    public void doChain(AvMsgHandleEvent event) {
        News news = event.getNews();
        Map<String, Object> body = news.getMessage().getBody();
        String msgCode = (String) body.get(MsgTypeEnum.META);
        if (ObjectUtil.isNotEmpty(body) && ObjectUtil.equal(msgCode, MsgTypeEnum.ReqSponsor.getCODE())) {
            final ReqOffer reqOffer = BeanUtil.copyProperties(body, ReqOffer.class);
            //判断对方状态是否占线
            FuncUtils.isTrueOrFalse(roomManage.isBusy(news.getTo())).trueOrFalseHandle(() -> {
                //创建房间
                final AbsRoom room = roomManage.getRoomFactory().create(reqOffer.getRoomCode());
                final IcomClient client = roomManage.getBeanResolvable().getClient(news.getFrom());
                client.putOnRoom(room);
                final SrsRpcOfferDTO dto = BeanUtil.copyProperties(reqOffer, SrsRpcOfferDTO.class);
                dto.setFrom(news.getFrom());
                dto.setTo(news.getTo());
                dto.setCmd(news.getMessage().getCmd());
                CompletableFuture<FutureAnswer> completableFuture = srsRpcService.sdp(dto);
                completableFuture.thenAcceptAsync(it -> {
                    final News reNew = BeanUtil.copyProperties(it, News.class);
                    final Message message = Message.builder().cmd(it.getCmd()).build();
                    FuncUtils.isTrueOrFalse(it.getCode() == 0)
                            .trueOrFalseHandle(() -> {
                                message.setBody((BeanUtil.beanToMap(it.getRespAnswer())));//推送
                            }, () -> {
                                RespError error = NewsHelper.Error(ErrorCodeEnum.UNKNOWN_SDP_ERROR);
                                message.setBody(BeanUtil.beanToMap(error));
                            });
                    reNew.setMessage(message);
                    roomManage.getSession(it.getFrom()).sendText(JsonUtils.pojoToJson(reNew));
                });
            }, () -> {//对方占线
                final RespBusy respBusy = RespBusy.builder().msgType(MsgTypeEnum.RespBusy.CODE).build();
                news.getMessage().setBody(BeanUtil.beanToMap(respBusy));
                roomManage.getSession(news.getFrom()).sendText(JsonUtils.pojoToJson(news));
            });
        } else {
            doChain(event);
        }
    }
}
