package com.izouma.nineth.web;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/restCache")
@AllArgsConstructor
@Slf4j
public class RedisCacheController {
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/scan")
    public Iterable<String> scan(String key) {

        return redisTemplate.execute((RedisCallback<Iterable<String>>) connection -> {

            List<String> keys = new ArrayList<>();

            Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions()
                    .count(1000)
                    .match(key)
                    .build());
            while (cursor.hasNext()) {
                keys.add(new String(cursor.next()));
            }

            cursor.close();

            return keys;
        });

    }
}
