package com.izouma.nineth.listener;

import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.service.CollectionService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@Slf4j
@AllArgsConstructor
@RocketMQMessageListener(
        consumerGroup = "${general.update-stock-group}",
        topic = "${general.update-stock-topic}",
        consumeMode = ConsumeMode.ORDERLY)
@ConditionalOnProperty(value = "general.notify-server", havingValue = "true")
public class UpdateStockListener implements RocketMQListener<Long> {

    private CollectionService             collectionService;
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(Long id) {
        BoundHashOperations<String, String, Integer> ops = redisTemplate.boundHashOps(RedisKeys.UPDATE_STOCK);
        ops.increment(id.toString(), 1);
    }

    @Scheduled(fixedRate = 10000)
    public void updateSale() {
        BoundHashOperations<String, String, Integer> ops = redisTemplate.boundHashOps(RedisKeys.UPDATE_STOCK);
        Set<String> keys = ops.keys();
        if (keys != null) {
            for (String id : keys) {
                Long val = ops.increment(id, -1);
                if (val <= 0) {
                    ops.delete(id);
                } else if (val > 1) {
                    ops.put(id, 1);
                }
                collectionService.syncStock(Long.parseLong(id));
            }
        }
    }
}
