package com.red.circle.other.infra.database.rds.service.props.impl;

import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.props.PropsStealthBrowseDAO;
import com.red.circle.other.infra.database.rds.entity.props.PropsStealthBrowse;
import com.red.circle.other.infra.database.rds.service.props.PropsStealthBrowseService;
import com.red.circle.tool.core.date.TimestampUtils;
import java.sql.Timestamp;
import java.util.Objects;
import java.util.Optional;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 隐身浏览 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-06-27
 */
@Service
public class PropsStealthBrowseServiceImpl extends
    BaseServiceImpl<PropsStealthBrowseDAO, PropsStealthBrowse> implements
    PropsStealthBrowseService {

  @Override
  public boolean saveOrUpdate(Long userId, Integer appendDays) {
    PropsStealthBrowse roomLock = query().eq(PropsStealthBrowse::getUserId, userId)
        .last(PageConstant.LIMIT_ONE)
        .getOne();

    if (Objects.nonNull(roomLock)) {
      roomLock
          .setExpireTime(TimestampUtils.expiredPlusDays(roomLock.getExpireTime(), appendDays));
      return updateSelectiveById(roomLock);
    }

    return save(new PropsStealthBrowse()
        .setUserId(userId)
        .setExpireTime(TimestampUtils.nowPlusDays(appendDays))
    );
  }

  @Override
  public Timestamp getExpireTime(Long userId) {
    return Optional.ofNullable(
        query().select(PropsStealthBrowse::getExpireTime)
            .eq(PropsStealthBrowse::getUserId, userId)
            .gt(PropsStealthBrowse::getExpireTime, TimestampUtils.now())
            .last(PageConstant.LIMIT_ONE)
            .getOne()
    ).map(PropsStealthBrowse::getExpireTime).orElse(null);
  }

  @Override
  public boolean existsNotExpire(Long userId) {
    return Optional.ofNullable(query().select(PropsStealthBrowse::getId)
        .eq(PropsStealthBrowse::getUserId, userId)
        .gt(PropsStealthBrowse::getExpireTime, TimestampUtils.now())
        .last(PageConstant.LIMIT_ONE)
        .getOne()
    ).map(propsRoomLock -> Objects.nonNull(propsRoomLock.getId())).orElse(Boolean.FALSE);
  }
}
