package com.xunhong.erp.turbo.captcha.service;

import com.anji.captcha.service.CaptchaCacheService;
import lombok.Setter;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 对于分布式部署的应用，我们建议应用自己实现CaptchaCacheService，比如用Redis，参考service/spring-boot代码示例。
 * 如果应用是单点的，也没有使用redis，那默认使用内存。
 * 内存缓存只适合单节点部署的应用，否则验证码生产与验证在节点之间信息不同步，导致失败。
 */
@Setter
public class CaptchaCacheServiceRedisImpl implements CaptchaCacheService {

	private static final String LUA_SCRIPT = "local key = KEYS[1] " +
		"local incrementValue = tonumber(ARGV[1]) " +
		"if redis.call('EXISTS', key) == 1 then " +
		"    return redis.call('INCRBY', key, incrementValue) " +
		"else " +
		"    return incrementValue " +
		"end";
	private RedissonClient redissonClient;

	@Override
	public String type() {
		return "redis";
	}

	@Override
	public void set(String key, String value, long expiresInSeconds) {
		redissonClient.getBucket(key).set(value, expiresInSeconds, TimeUnit.SECONDS);
	}

	@Override
	public boolean exists(String key) {
		return redissonClient.getBucket(key).isExists();
	}

	@Override
	public void delete(String key) {
		redissonClient.getBucket(key).delete();
	}

	@Override
	public String get(String key) {
		return (String) redissonClient.getBucket(key).get();
	}

	@Override
	public Long increment(String key, long val) {
		return redissonClient.getScript().eval(RScript.Mode.READ_WRITE, LUA_SCRIPT, RScript.ReturnType.INTEGER);
	}
}
