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

import com.red.circle.other.infra.database.mongo.entity.live.StatisticsRoomActive;
import com.red.circle.other.infra.database.mongo.service.live.StatisticsRoomActiveService;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
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 2022/3/24
 */
@Service
@RequiredArgsConstructor
public class StatisticsRoomActiveServiceImpl implements StatisticsRoomActiveService {

  private final MongoTemplate mongoTemplate;

  @Override
  public void add(StatisticsRoomActive statisticsRoomActive) {
    mongoTemplate.save(statisticsRoomActive);
  }

  @Override
  public List<StatisticsRoomActive> listByTimeRange(Long roomId, Timestamp startTime,
      Timestamp endTime) {
    Criteria criteria = Criteria.where("roomId").is(roomId);
    criteria.andOperator(
        Criteria.where("createTime").gte(startTime),
        Criteria.where("createTime").lte(endTime)
    );
    Query query = Query.query(criteria)
        .with(Sort.by(Sort.Order.asc("createTime")));
    return mongoTemplate
        .find(query, StatisticsRoomActive.class);
  }

  @Override
  public Timestamp getLatestActiveTime(Long roomId) {
    return Optional.ofNullable(mongoTemplate
            .findOne(Query.query(Criteria.where("roomId").is(roomId))
                    .with(Sort.by(Sort.Order.desc("createTime")))
                    .limit(1),
                StatisticsRoomActive.class))
        .map(StatisticsRoomActive::getCreateTime)
        .orElse(null);
  }
}
