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

import com.google.common.collect.Lists;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.relation.friendcard.UserFriendCardApplyCO;
import com.red.circle.other.app.dto.cmd.user.relation.friendcard.FriendshipCardPageCmd;
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.FriendshipCard;
import com.red.circle.other.infra.database.rds.service.user.user.FriendshipCardService;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 友谊关系卡 - 存在关系列表 .
 * </p>
 *
 * @author pengshigang
 * @since 2022-06-20
 */
@Component
@RequiredArgsConstructor
public class UserFriendCardAgreePageQryExe {

  private final FriendshipCardService friendshipCardService;
  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;

  public List<UserFriendCardApplyCO> execute(FriendshipCardPageCmd cmd) {

    List<FriendshipCard> friendshipCards = getPageByCondition(cmd);

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

    return friendshipCards.stream().map(card -> {

      UserProfile userProfile = userProfileGateway.getByUserId(card.getSendUserId());
      if (Objects.isNull(userProfile)) {
        return null;
      }

      return new UserFriendCardApplyCO()
          .setId(card.getId())
          .setStatus("")
          .setCardType(card.getCardType())
          .setApplyDesc(card.getCardType())
          .setCreateTime(TimestampUtils.convert(card.getCreateTime()))
          .setUserProfile(userProfileAppConvertor.toUserProfileDTO(userProfile));

    }).filter(Objects::nonNull).collect(Collectors.toList());

  }

  private List<FriendshipCard> getPageByCondition(FriendshipCardPageCmd cmd) {
    return friendshipCardService.pageByCondition(cmd.getPageNumber(), null,
        cmd.requiredReqUserId());
  }

}
