package com.izouma.nineth.service;

import com.izouma.nineth.dto.Captcha;
import com.pig4cloud.captcha.ArithmeticCaptcha;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.ehcache.UserManagedCache;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.UserManagedCacheBuilder;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.IOException;
import java.time.Duration;
import java.util.UUID;

@Service
@AllArgsConstructor
public class CaptchaService {
    private final UserManagedCache<String, String> captchaCache =
            UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, String.class)
                    .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(10)))
                    .build(true);

    public Captcha gen() throws IOException, FontFormatException {
        String key = UUID.randomUUID().toString();
//        SpecCaptcha specCaptcha = new SpecCaptcha(90 * 2, 32 * 2, 5);
//        specCaptcha.setFont(com.wf.captcha.base.Captcha.FONT_7, 24 * 2);
//        String code = specCaptcha.text().toLowerCase();
//        String image = specCaptcha.toBase64();
//        captchaCache.put(key, code);

        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(150, 48);
        captcha.setFont(6, 15 * 2);
        captcha.setLen(2);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        captcha.supportAlgorithmSign(2); // 可设置支持的算法：2 表示只生成带加减法的公式
        captcha.setDifficulty(99); // 设置计算难度，参与计算的每一个整数的最大值
        String code = captcha.text();  // 获取运算的结果：5
        String image = captcha.toBase64();  // 输出验证码
        captchaCache.put(key, code);
        return new Captcha(key, image);
    }

    public boolean verify(String key, String code) {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) {
            return false;
        }
        code = code.toLowerCase();
        boolean verify = false;
        String trueCode = captchaCache.get(key);
        if (StringUtils.isNotBlank(trueCode) && trueCode.equals(code)) {
            verify = true;
        }
        return verify;
    }
}
