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

import com.google.common.collect.Lists;
import com.red.circle.other.infra.database.mongo.entity.live.RoomTourist;
import com.red.circle.other.infra.database.mongo.service.live.RoomTouristService;
import com.red.circle.tool.core.date.TimestampUtils;
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.stereotype.Service;

/**
 * 房间足迹 实现.
 *
 * @author pengliang on 2021/12/27
 */
@Service
@RequiredArgsConstructor
public class RoomTouristServiceImpl implements RoomTouristService {

  private final MongoTemplate mongoTemplate;

  @Override
  public void add(Long userId, Long roomId, Long timeId) {
    mongoTemplate.save(new RoomTourist()
        .setId(userId + "_" + roomId)
        .setTimeId(timeId)
        .setUserId(userId)
        .setRoomId(roomId)
        .setCreateTime(TimestampUtils.now())
        .setExpiredTime(TimestampUtils.nowPlusDays(7))
    );
  }

  @Override
  public List<RoomTourist> flow(Long userId, Long lastTimeId) {
    if (Objects.isNull(userId)) {
      return Lists.newArrayList();
    }
    Criteria criteria = Criteria.where("userId").is(userId);
    if (Objects.nonNull(lastTimeId)) {
      criteria.and("timeId").lt(lastTimeId);
    }
    return mongoTemplate.find(Query.query(criteria)
        .with(Sort.by(Sort.Order.desc("timeId")))
        .limit(20), RoomTourist.class);
  }

  @Override
  public List<RoomTourist> listRecentVisitors(Long roomId, Long userId) {
    if (Objects.isNull(roomId)) {
      return Lists.newArrayList();
    }
    Criteria criteria = Criteria.where("roomId").is(roomId);
    if (Objects.nonNull(userId)) {
      criteria.and("userId").is(userId);
    }
    return mongoTemplate.find(Query.query(criteria)
        .with(Sort.by(Sort.Order.desc("createTime")))
        .limit(2000), RoomTourist.class);
  }

}
