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.mongo.entity.live.RoomTourist;
import com.red.circle.other.infra.database.mongo.service.live.RoomTouristService;
import com.red.circle.other.infra.database.rds.entity.live.RoomSubscription;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 我的足迹
 *
 * @author pengliang on 2021/2/21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserTraceRoomsQryExe {

  private final RoomTouristService roomTouristService;
  private final RoomVoiceProfileCommon roomVoiceProfileCommon;
  private final GameLudoService gameLudoService;

  public List<RoomBrowseRecordsV2CO> execute(AppFlowCmd cmd) {
    List<RoomTourist> roomTourists = roomTouristService
        .flow(cmd.requiredReqUserId(), cmd.getLastId());
    if (CollectionUtils.isEmpty(roomTourists)) {
      return Lists.newArrayList();
    }

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

    Map<Long, RoomVoiceProfileCO> roomProfileMap = roomVoiceProfileCommon.mapRoomVoiceProfile(
        roomTourists.stream().map(RoomTourist::getRoomId).collect(Collectors.toSet()));
    return roomTourists.stream().filter(Objects::nonNull)
        .map(roomTourist -> {
          RoomVoiceProfileCO profileCO = roomProfileMap.get(roomTourist.getRoomId());
          if (profileCO != null) {
            profileCO.setRoomGameIcon(coverMap.get(roomTourist.getRoomId()));
          }

            return new RoomBrowseRecordsV2CO()
                            .setId(roomTourist.getTimeId())
                            .setRoomProfile(profileCO);
                }
        ).filter(record -> Objects.nonNull(record.getRoomProfile()))
        .collect(Collectors.toList());
  }

}
