package cn.reghao.oss.console.account.service;

import cn.reghao.oss.console.util.CaptchaUtil;
import cn.reghao.oss.console.util.CacheKeys;
import cn.reghao.jutil.jdk.security.RandomString;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author reghao
 * @date 2022-04-26 20:24:58
 */
@Slf4j
@Service
public class CodeService {
    private final long sessionTimeout;
    private final Cache<String, Object> caffeineCache;

    public CodeService(ServerProperties serverProperties, Cache<String, Object> caffeineCache) {
        this.sessionTimeout = serverProperties.getServlet().getSession().getTimeout().getSeconds();
        this.caffeineCache = caffeineCache;
    }

    public InputStream generateCaptcha() throws IOException {
        String captchaCode = RandomString.getString(5);
        caffeineCache.put(CacheKeys.getCaptchaKey(), captchaCode);

        ByteArrayOutputStream baos = CaptchaUtil.captchaWithDisturb(captchaCode, 130, 48);
        return new ByteArrayInputStream(baos.toByteArray());
    }

    public String getCaptcha() {
        return (String) caffeineCache.getIfPresent(CacheKeys.getCaptchaKey());
    }
}
