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.UserSupportRelationCO;
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.UserSubscription;
import com.red.circle.other.infra.database.rds.service.user.user.UserSubscriptionService;

import java.util.*;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 用户关系订阅列表
 *
 * @author pengliang on 2020/11/11
 */
@Component
@RequiredArgsConstructor
public class UserRelationFollowQryExe {

  private final PropsUserAppConvertor propsUserAppConvertor;
  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final UserSubscriptionService userSubscriptionService;

  public List<UserSupportRelationCO> execute(AppFlowCmd cmd) {
    Long subscriptionUserId = null;
    if (StringUtils.hasText(cmd.getAccount())) {
      subscriptionUserId = Optional.ofNullable(userProfileGateway.getByAccount(cmd.getReqSysOrigin().getOrigin(), cmd.getAccount()))
              .map(UserProfile::getId)
              .orElse(-1L);
    }

    List<UserSubscription> userSubscriptions = userSubscriptionService
        .listByUserId(cmd.requiredReqUserId(), cmd.getLastId(), subscriptionUserId);

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

    Map<Long, UserProfile> userProfileMap = userProfileGateway
        .mapByUserIds(getSubscribeUserId(userSubscriptions));

    return userSubscriptions.stream()
        .map(userSubscription -> {
          UserProfile userProfile = userProfileMap.get(userSubscription.getSubscribeUserId());
          return new UserSupportRelationCO()
              .setId(userSubscription.getId())
              .setUserProfile(userProfileAppConvertor.toUserProfileDTO(userProfile))
              .setMutualRelations(userSubscription.getMutualRelations())
              .setUseProps(propsUserAppConvertor.toListUsePropsDTO(userProfile.getUseProps()));
        })
        .collect(Collectors.toList());
  }

  private Set<Long> getSubscribeUserId(List<UserSubscription> userSubscriptions) {
    return userSubscriptions.stream().map(UserSubscription::getSubscribeUserId)
        .collect(Collectors.toSet());
  }
}
