package com.red.circle.other.infra.database.mongo.service.user.friend.impl;

import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.other.infra.database.mongo.entity.user.friend.FriendApplyStatus;
import com.red.circle.other.infra.database.mongo.entity.user.friend.FriendsApply;
import com.red.circle.other.infra.database.mongo.service.user.friend.FriendsApplyListService;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * 好友申请列表 实现.
 *
 * @author pengliang on 2021/5/6
 */
@Service
@RequiredArgsConstructor
public class FriendsApplyListServiceImpl implements FriendsApplyListService {

  private final MongoTemplate mongoTemplate;

  @Override
  public void add(FriendsApply friendsApply) {
    friendsApply.generateId();
    mongoTemplate.save(friendsApply);
  }

  @Override
  public void changeStatus(Long userId, Long applyUserId, FriendApplyStatus status) {
    mongoTemplate.updateFirst(Query.query(Criteria.where("userId").is(userId)
            .and("applyUserId").is(applyUserId)),
        new Update().set("status", status), FriendsApply.class);
  }

  @Override
  public List<FriendsApply> flow(Long userId, Long lastTimingId) {
    Criteria criteria = Criteria.where("userId").is(userId);
    if (Objects.nonNull(lastTimingId)) {
      criteria.and("timingId").lt(lastTimingId);
    }
    return mongoTemplate
        .find(Query.query(criteria).with(Sort.by(Sort.Order.desc("timingId")))
            .limit(PageConstant.DEFAULT_LIMIT_SIZE), FriendsApply.class);
  }

  @Override
  public Long countFriendsApply(Long userId) {
    Criteria criteria = Criteria.where("userId").is(userId).and("status")
        .is(FriendApplyStatus.FRIEND_APPLY);
    return mongoTemplate.count(Query.query(criteria), FriendsApply.class);
  }

}
