package com.red.circle.other.app.command.room.query;

import com.google.common.collect.Lists;
import com.red.circle.common.business.dto.cmd.app.AppFlowCmd;
import com.red.circle.other.app.common.room.RoomVoiceProfileCommon;
import com.red.circle.other.app.dto.clientobject.room.RoomBrowseRecordsV2CO;
import com.red.circle.other.app.dto.clientobject.room.RoomVoiceProfileCO;
import com.red.circle.other.infra.database.rds.entity.live.RoomMember;
import com.red.circle.other.infra.database.rds.service.live.RoomMemberService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 已加入在房间.
 *
 * @author pengliang on 2021/2/21
 */
@Component
@RequiredArgsConstructor
public class UserJoinedRoomsQryExe {

  private final RoomMemberService roomMemberService;
  private final RoomVoiceProfileCommon roomVoiceProfileCommon;

  public List<RoomBrowseRecordsV2CO> execute(AppFlowCmd cmd) {
    List<RoomMember> roomMembers = roomMemberService
        .listRoomIdExcludeHomeownerByUserIdFlow(cmd.requiredReqUserId(), cmd.getLastId());
    if (CollectionUtils.isEmpty(roomMembers)) {
      return Lists.newArrayList();
    }
    Map<Long, RoomVoiceProfileCO> roomProfileMap = roomVoiceProfileCommon.mapRoomVoiceProfile(
        roomMembers.stream().map(RoomMember::getRoomId).collect(Collectors.toSet()));
    return roomMembers.stream().map(roomMember -> new RoomBrowseRecordsV2CO()
            .setId(roomMember.getId())
            .setRoomProfile(roomProfileMap.get(roomMember.getRoomId())))
        .filter(record -> Objects.nonNull(record.getRoomProfile()))
        .collect(Collectors.toList());
  }
}
