package com.red.circle.other.app.command.material.query;

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.convertor.material.EmojiAppConvertor;
import com.red.circle.other.app.dto.clientobject.material.UserEmojiBagCO;
import com.red.circle.other.infra.database.cache.entity.material.UserEmojiBackpackCache;
import com.red.circle.other.infra.database.cache.service.other.EmojiCacheService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 获取用户背包，返回所有.
 *
 * @author pengliang on 2021/10/25
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EmojiAllQryExe {

  private final EmojiCacheService emojiCacheService;
  private final EmojiAppConvertor emojiAppConvertor;


  public List<UserEmojiBagCO> execute(AppExtCommand cmd) {
    List<UserEmojiBackpackCache> emojiBackpackCaches = listUserEmojiBackpackCache(cmd);

    if (CollectionUtils.isEmpty(emojiBackpackCaches)) {
      return CollectionUtils.newArrayList();
    }
    return emojiAppConvertor.toListUserEmojiBagCO(emojiBackpackCaches.stream()
        .sorted(Comparator.comparing(UserEmojiBackpackCache::getHave, Comparator.reverseOrder())
            .thenComparing(UserEmojiBackpackCache::getSort, Comparator.reverseOrder()))
        .collect(Collectors.toList()));
  }

  public List<UserEmojiBackpackCache> listUserEmojiBackpackCache(AppExtCommand cmd) {
    List<UserEmojiBackpackCache> emojiBackpackCaches = emojiCacheService.listEmojiAll(cmd.requireReqSysOrigin());

    List<Long> emojiBagIds = emojiCacheService.listEmojiBagIds(cmd.requiredReqUserId());

    if (CollectionUtils.isEmpty(emojiBagIds)) {
      return emojiBackpackCaches;
    }

    return emojiBackpackCaches.stream().peek(cache -> {
      if (emojiBagIds.contains(cache.getId())) {
        cache.setHave(Boolean.TRUE);
      }
    }).collect(Collectors.toList());
  }

}
