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.GiveFriendshipCardApply;
import com.red.circle.other.infra.database.rds.service.user.user.GiveFriendshipCardApplyService;
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-10
 */
@Component
@RequiredArgsConstructor
public class UserFriendCardApplyPageQryExe {

  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final GiveFriendshipCardApplyService giveFriendshipCardApplyService;

  public List<UserFriendCardApplyCO> execute(FriendshipCardPageCmd cmd) {

    List<GiveFriendshipCardApply> applyList = getPageByCondition(cmd);

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

    return applyList.stream().map(apply -> {

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

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

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

  }

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

}
