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

import com.google.common.collect.Lists;
import com.red.circle.common.business.dto.cmd.app.AppFlowCmd;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.app.convertor.user.PropsUserAppConvertor;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.relation.friend.UserFriendCO;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.rds.entity.user.user.RelationshipFriend;
import com.red.circle.other.infra.database.rds.service.user.user.RelationshipFriendService;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 好友列表查看.
 *
 * @author pengliang on 2021/5/7
 */
@Component
@RequiredArgsConstructor
public class UserFriendListQryExe {

  private final PropsUserAppConvertor propsUserAppConvertor;
  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final RelationshipFriendService relationshipFriendService;

  public List<UserFriendCO> execute(AppFlowCmd cmd) {
    Long friendUserId = null;
    if (StringUtils.isNotBlank(cmd.getAccount())){
      UserProfile userProfile = userProfileGateway.getByAccount(cmd.getReqSysOrigin().getOrigin(), cmd.getAccount());
      friendUserId = userProfile.getId();
    }

    List<RelationshipFriend> relationshipFriends = relationshipFriendService
        .flowSize1000(cmd.requiredReqUserId(), cmd.getLastId(),friendUserId);

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

    Map<Long, UserProfile> userProfileMap = userProfileGateway
        .mapByUserIds(getFriendUserIds(relationshipFriends));
    return relationshipFriends.stream().map(relationshipFriend -> {
          UserProfile userProfile = userProfileMap.get(relationshipFriend.getFriendUserId());
          return new UserFriendCO()
              .setId(relationshipFriend.getId())
              .setUserProfile(userProfileAppConvertor.toUserProfileDTO(userProfile))
              .setUseProps(propsUserAppConvertor.toListUsePropsDTO(userProfile.getUseProps()));
        })
        .collect(Collectors.toList());
  }

  private Set<Long> getFriendUserIds(List<RelationshipFriend> relationshipFriends) {
    return relationshipFriends.stream().map(RelationshipFriend::getFriendUserId)
        .collect(Collectors.toSet());
  }
}
