package com.red.circle.live.infra.database.cache.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.live.domain.live.LiveHeartbeat;
import com.red.circle.live.infra.database.cache.key.LiveHeartbeatKey;
import com.red.circle.live.infra.database.cache.service.LiveHeartbeatCacheService;
import com.red.circle.tool.core.json.JacksonUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class LiveHeartbeatCacheServiceImpl implements LiveHeartbeatCacheService {

  private final RedisService redisService;


  @Override
  public void create(Long roomId, List<LiveHeartbeat> list) {
    if(Objects.isNull(list)) {
      redisService.delete(LiveHeartbeatKey.ROOM.getKey(roomId));
      return;
    }
    redisService.setString(LiveHeartbeatKey.ROOM.getKey(roomId), JacksonUtils.toJson(list));
  }

  @Override
  public List<LiveHeartbeat> listLiveHeartbeat(Long roomId) {
    String LiveHeartbeatStr = redisService.getString(LiveHeartbeatKey.ROOM.getKey(roomId));
    return Optional.ofNullable(JacksonUtils.readValue(LiveHeartbeatStr, new
        TypeReference<List<LiveHeartbeat>>() {
        })).orElse(Lists.newArrayList());
  }
}
