package com.red.circle.other.infra.database.rds.service.emoji.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.emoji.EmojiBagDAO;
import com.red.circle.other.infra.database.rds.entity.emoji.EmojiBag;
import com.red.circle.other.infra.database.rds.service.emoji.EmojiBagService;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表情背包 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-10-25
 */
@Service
public class EmojiBagServiceImpl extends BaseServiceImpl<EmojiBagDAO, EmojiBag> implements
    EmojiBagService {

  @Override
  public List<EmojiBag> listByUserId(Long userId) {
    return query()
        .eq(EmojiBag::getUserId, userId)
        .last(PageConstant.DEFAULT_LIMIT)
        .list();
  }

  @Override
  public void add(Long userId, Long emojiId) {
    if (exists(userId, emojiId)) {
      return;
    }
    save(new EmojiBag()
        .setUserId(userId)
        .setEmojiId(emojiId)
    );
  }

  @Override
  public boolean existEmoji(Long userId, Long emojiId) {
    return exists(userId, emojiId);
  }

  private boolean exists(Long userId, Long emojiId) {
    return Optional.ofNullable(query()
            .select(EmojiBag::getId)
            .eq(EmojiBag::getUserId, userId)
            .eq(EmojiBag::getEmojiId, emojiId)
            .last(PageConstant.LIMIT_ONE)
            .getOne())
        .map(emojiBag -> Objects.nonNull(emojiBag.getId()))
        .orElse(Boolean.FALSE);
  }
}
