package com.red.circle.other.app.common.room;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.enums.SVIPLevelEnum;
import com.red.circle.other.app.convertor.live.RoomProfileAppConvertor;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.room.RoomVoiceProfileCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.live.ActiveVoiceRoom;
import com.red.circle.other.infra.database.mongo.entity.live.RoomProfileManager;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.inner.model.dto.material.UseBadgeDTO;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 语音房间资料.
 *
 * @author pengliang on 2021/2/20
 */
@Service
@RequiredArgsConstructor
public class RoomVoiceProfileCommon {

  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final RoomProfileAppConvertor roomProfileAppConvertor;
  private final RoomProfileManagerService roomProfileManagerService;


  public List<RoomVoiceProfileCO> listRoomVoiceProfilesV2(Set<Long> roomIds) {
    return listRoomVoiceProfilesV2(roomProfileManagerService.listByRoomIds(roomIds));
  }

  public List<RoomVoiceProfileCO> listRoomVoiceProfilesV2(
          List<RoomProfileManager> roomProfileManagers) {
    if (CollectionUtils.isEmpty(roomProfileManagers)) {
      return Lists.newArrayList();
    }

    Map<Long, UserProfileDTO> userProfileMap = userProfileAppConvertor.toMapUserProfileDTO(
            userProfileGateway.mapByUserIds(
                    roomProfileManagers.stream().map(RoomProfileManager::getUserId)
                            .collect(Collectors.toSet())));

    return roomProfileManagers.stream()
            .map(roomManager -> mergeRoomVoiceProfile(userProfileMap.get(roomManager.getUserId()),
                    roomManager))
            .toList();
  }

  public Map<Long, RoomVoiceProfileCO> mapRoomVoiceProfile(Set<Long> roomIds) {
    if (CollectionUtils.isEmpty(roomIds)) {
      return Maps.newHashMap();
    }
    return Optional.ofNullable(this.listRoomVoiceProfilesV2(roomIds))
            .map(roomProfiles -> roomProfiles.stream()
                    .collect(Collectors.toMap(RoomVoiceProfileCO::getId, val -> val)))
            .orElse(Maps.newHashMap());
  }

  public RoomVoiceProfileCO getAvailableByRoomAccount(SysOriginPlatformEnum sysOrigin,
                                                      String roomAccount) {
    return Optional.ofNullable(
                    userProfileAppConvertor.toUserProfileDTO(
                            userProfileGateway.getByAccount(sysOrigin.name(), roomAccount)
                    )
            )
            .map(userProfile -> {
              RoomProfileManager manager = roomProfileManagerService.getByUserId(userProfile.getId());
              if (Objects.nonNull(manager)) {
                if (Objects.equals(manager.getDel(), Boolean.TRUE)) {
                  return null;
                }
                return mergeRoomVoiceProfile(userProfile, manager);
              }

              return null;
            }).orElse(null);
  }

  public List<RoomVoiceProfileCO> toListRoomVoiceProfileCO(List<ActiveVoiceRoom> activeVoiceRooms) {
    if (CollectionUtils.isEmpty(activeVoiceRooms)) {
      return Lists.newArrayList();
    }

    Map<Long, RoomProfileManager> roomProfileManagerMap = roomProfileManagerService.mapByRoomIds(
            activeVoiceRooms.stream().map(ActiveVoiceRoom::getId).collect(Collectors.toSet()));

    if (CollectionUtils.isEmpty(roomProfileManagerMap)) {
      return Lists.newArrayList();
    }

    Map<Long, UserProfileDTO> userProfileMap = userProfileAppConvertor.toMapUserProfileDTO(
            userProfileGateway.mapByUserIds(
                    activeVoiceRooms.stream().map(ActiveVoiceRoom::getUserId)
                            .collect(Collectors.toSet()))
    );

    return activeVoiceRooms.stream()
            .map(roomManager -> mergeActiveVoiceRoom(
                    userProfileMap.get(roomManager.getUserId()),
                    roomProfileManagerMap.get(roomManager.getId()),
                    roomManager
            ))
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
  }

  private RoomVoiceProfileCO mergeActiveVoiceRoom(UserProfileDTO userProfile,
                                                  RoomProfileManager manager,
                                                  ActiveVoiceRoom activeVoiceRoom) {

    if (Objects.isNull(userProfile) || Objects.isNull(manager) || Objects.isNull(activeVoiceRoom)) {
      return null;
    }

    RoomVoiceProfileCO roomVoiceProfile = mergeRoomVoiceProfile(userProfile, manager);
    if (Objects.isNull(roomVoiceProfile)) {
      return null;
    }
    roomVoiceProfile.setHotRoom(activeVoiceRoom.getHot());
    roomVoiceProfile.setRoomGameIcon("");
    roomVoiceProfile.setUserSVipLevel(SVIPLevelEnum.valueOf(activeVoiceRoom.getSuperVipLevel()));
    return roomVoiceProfile;
  }

  private RoomVoiceProfileCO mergeRoomVoiceProfile(UserProfileDTO userProfile,
                                                   RoomProfileManager manager) {

    if (Objects.isNull(manager)) {
      return null;
    }

    RoomVoiceProfileCO roomVoiceProfile = roomProfileAppConvertor.toRoomVoiceProfileCO(manager);
    roomVoiceProfile.setUserProfile(userProfile);
    roomVoiceProfile
            .putExistsPassword(StringUtils.isNotBlank(manager.getSetting().getPassword()))
            .putRoomDefaultSetting(roomProfileAppConvertor.toRoomSettingCO(manager.getSetting()))
            .putRoomMemberQuantity(manager.getCounter().getMemberCount());
    roomVoiceProfile.setRoomBadgeIcons(Optional.ofNullable(manager.getUseBadges()).map(
            badges -> badges.stream().map(UseBadgeDTO::getSelectUrl)
                    .toList()).orElse(Lists.newArrayList())
    );
    // 兼容Android进入自己房间错误
    roomVoiceProfile.setLayoutKey("");
    return roomVoiceProfile;
  }


}
