package com.red.circle.live.infra.listener;

import com.red.circle.component.redis.listener.RedisKeyExpiredMessageListener;
import com.red.circle.live.domain.gateway.LiveMicrophoneGateway;
import com.red.circle.live.infra.database.cache.key.LiveMicKey;
import com.red.circle.live.infra.database.cache.service.LiveMicUserCacheService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.parse.DataTypeUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 监听Redis key 过期. 注意: 依赖系统配置notify-keyspace-events=Ex
 *
 * @author pengliang on 2023/12/25
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MicRoomKeyExpiredMessageListener implements RedisKeyExpiredMessageListener {

  private final LiveMicrophoneGateway liveMicrophoneGateway;
  private final LiveMicUserCacheService liveMicUserCacheService;

  @Override
  public String listenerKey() {
    return LiveMicKey.SEAT.getKey("*");
  }

  @Override
  public void onMessage(String key) {
    // log.warn("keyExpiredMessage: {}", key);
    List<String> items = Arrays.stream(key.split(":")).filter(StringUtils::isNotBlank).toList();
    if (CollectionUtils.isEmpty(items)) {
      return;
    }
    Long roomId = DataTypeUtils.toLong(items.get(items.size() - 1));
    if (Objects.isNull(roomId) || roomId <= 0) {
      log.warn("KeyExpiredMessage Data error: {}", key);
      return;
    }
    liveMicrophoneGateway.micUserChangeNotice(roomId);
    liveMicUserCacheService.remove(roomId);
  }

}
