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

import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.other.app.common.room.RoomVoiceProfileCommon;
import com.red.circle.other.app.dto.clientobject.room.RoomVoiceProfileCO;
import com.red.circle.other.app.dto.cmd.room.RegionSearchRoomQryCmd;
import com.red.circle.other.infra.database.mongo.entity.live.ActiveVoiceRoom;
import com.red.circle.other.infra.database.mongo.service.live.ActiveVoiceRoomService;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.tool.core.collection.CollectionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 获取区域房间.
 *
 * @author pengliang on 2021/3/10
 */
@Component
@RequiredArgsConstructor
public class SearchRegionRoomQryExe {

  private final ActiveVoiceRoomService activeVoiceRoomService;
  private final RoomVoiceProfileCommon roomVoiceProfileCommon;
  private final RoomProfileManagerService roomProfileManagerService;

  public List<RoomVoiceProfileCO> execute(RegionSearchRoomQryCmd cmd) {

    List<ActiveVoiceRoom> activeVoiceRooms = activeVoiceRoomService
            .listSearchCountryRoom(cmd.getReqSysOrigin().getOrigin(), cmd.getCountryCode(),
                    PageConstant.MAX_LIMIT_SIZE);

    if (CollectionUtils.isNotEmpty(activeVoiceRooms) && activeVoiceRooms.size() >= 100) {
      return assemblyRoomVoiceProfile(activeVoiceRooms);
    }

    if (CollectionUtils.isEmpty(activeVoiceRooms)) {
      return roomVoiceProfileCommon.listRoomVoiceProfilesV2(
              roomProfileManagerService.listSelectiveLimit100(cmd.requireReqSysOrigin(),
                      cmd.getCountryCode(), null));
    }

    List<RoomVoiceProfileCO> roomVoiceProfiles = assemblyRoomVoiceProfile(activeVoiceRooms);
    roomVoiceProfiles.addAll(roomVoiceProfileCommon.listRoomVoiceProfilesV2(
            roomProfileManagerService.listSelectiveLimit100(cmd.requireReqSysOrigin(),
                    cmd.getCountryCode(), activeVoiceRooms
                            .stream().map(ActiveVoiceRoom::getId).collect(Collectors.toList()))));
    return roomVoiceProfiles;
  }

  private List<RoomVoiceProfileCO> assemblyRoomVoiceProfile(
          List<ActiveVoiceRoom> activeVoiceRooms) {
    return roomVoiceProfileCommon.toListRoomVoiceProfileCO(activeVoiceRooms);
  }

}
