package com.sjyt.icom.asst.context.handle.room;

import com.sjyt.icom.asst.common.enums.RoomEnum;
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.message.VerifyClaims;
import com.sjyt.icom.asst.common.model.room.ExtraInfo;
import com.sjyt.icom.asst.common.model.room.Room;
import com.sjyt.icom.asst.service.impl.RoomManageService;
import com.sjyt.icom.asst.service.impl.StreamUrlServiceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @author: Tab
 * @date: 2022-06-26 17:24
 * @since 1.0.0
 */
@Slf4j
@Component
public class RoomFactoryOneHandle extends RoomFactoryHandle {

    @Autowired
    public RoomFactoryOneHandle(RoomManageService roomManage, StreamUrlServiceService urlService) {
        super(roomManage, urlService);
    }

    @Override
    public Room doChain(RoomFactoryHandleEvent event) {
        if (event.getRoomEnum().equals(RoomEnum.ONE2ONE)) {
            Room room = roomManage.create(RoomEnum.ONE2ONE);
            final NewsLetter news = event.getNewsLetter();
            final Message message = news.getMessage();
            final Map<String, Object> map = message.getBody();
            final String msgCode = Optional.ofNullable(map)
                    .map(body -> (String) body.get("msgType"))
                    .orElseGet(() -> {
                        log.error("创建房间失败，msgType为空");
                        return null;
                    });
            if (msgCode == null) {
                return null;
            }
            final VerifyClaims claims = VerifyClaims.builder()
                    .rid(room.getRid())
                    .roomCode(RoomEnum.ONE2ONE.CODE)
                    .from(news.getFrom())
                    .to(news.getTo())
                    .cmdCode(message.getCmd())
                    .msgCode(msgCode).build();
            ExtraInfo extraInfo = initRoomData(claims);
            return Optional.of(extraInfo).map(room::addExtraInfo).orElse(null);
        }
        return handle.doChain(event);
    }
}
