package com.red.circle.other.infra.database.rds.service.live.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.live.RoomSubscriptionDAO;
import com.red.circle.other.infra.database.rds.entity.live.RoomSubscription;
import com.red.circle.other.infra.database.rds.service.live.RoomSubscriptionService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 房间订阅 服务实现类.
 * </p>
 *
 * @author houyong
 * @since 2020-12-01
 */
@Service
@RequiredArgsConstructor
public class RoomSubscriptionServiceImpl extends
    BaseServiceImpl<RoomSubscriptionDAO, RoomSubscription> implements RoomSubscriptionService {


  @Override
  public boolean validFollow(Long userId, Long roomId) {
    return Optional.ofNullable(query()
            .select(RoomSubscription::getId)
            .eq(RoomSubscription::getUserId, userId)
            .eq(RoomSubscription::getRoomId, roomId)
            .getOne())
        .map(subscription -> Objects.nonNull(subscription.getId()))
        .orElse(Boolean.FALSE);
  }


  @Override
  public void remove(Long userId, Long roomId) {
    delete()
        .eq(RoomSubscription::getUserId, userId)
        .eq(RoomSubscription::getRoomId, roomId)
        .last(PageConstant.LIMIT_ONE)
        .execute();
  }

  @Override
  public void add(Long userId, Long roomId) {
    save(new RoomSubscription()
        .setUserId(userId)
        .setRoomId(roomId)
    );
  }

  @Override
  public List<RoomSubscription> listRoomIdByUserIdFlow(Long userId,
      Long lastId) {
    return Optional.ofNullable(
        query().eq(RoomSubscription::getUserId, userId)
            .lt(Objects.nonNull(lastId), RoomSubscription::getId, lastId)
            .last(PageConstant.DEFAULT_LIMIT)
            .orderByDesc(RoomSubscription::getId)
            .list()
    ).orElse(CollectionUtils.newArrayList());
  }

}
