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.app.service.game.GameLudoService;
import com.red.circle.other.infra.database.rds.entity.live.RoomSubscription;
import com.red.circle.other.infra.database.rds.service.live.RoomSubscriptionService;
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 UserFollowRoomsQryExe {

  private final RoomVoiceProfileCommon roomVoiceProfileCommon;
  private final RoomSubscriptionService roomSubscriptionService;
  private final GameLudoService gameLudoService;

  public List<RoomBrowseRecordsV2CO> execute(AppFlowCmd cmd) {
    List<RoomSubscription> roomSubscriptions = roomSubscriptionService
        .listRoomIdByUserIdFlow(cmd.requiredReqUserId(), cmd.getLastId());

    return CollectionUtils.isEmpty(roomSubscriptions)
        ? Lists.newArrayList()
        : assemblyRoomBrowseRecordsV2(roomSubscriptions);
  }

  private List<RoomBrowseRecordsV2CO> assemblyRoomBrowseRecordsV2(
      List<RoomSubscription> roomSubscriptions) {
    Map<Long, RoomVoiceProfileCO> roomProfileMap = roomVoiceProfileCommon.mapRoomVoiceProfile(
        roomSubscriptions.stream().map(RoomSubscription::getRoomId).collect(Collectors.toSet()));

    // 填充游戏图标
    List<Long> list = roomSubscriptions.stream().map(RoomSubscription::getRoomId).toList();
    Map<Long, String> coverMap = gameLudoService.listGameCoverByRoomIds(list);

    return roomSubscriptions.stream().map(roomMember -> {
                RoomVoiceProfileCO profileCO = roomProfileMap.get(roomMember.getRoomId());
                if (profileCO != null) {
                  profileCO.setRoomGameIcon(coverMap.get(roomMember.getRoomId()));
                }
                return new RoomBrowseRecordsV2CO()
                        .setId(roomMember.getId())
                        .setRoomProfile(profileCO);
            })
        .filter(sub -> Objects.nonNull(sub.getRoomProfile())).collect(Collectors.toList());
  }

}
