package com.dkl.framework.config;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import com.google.code.kaptcha.text.impl.DefaultTextCreator;

/**
 * 验证码文本生成器
 *
 * @author Dkl
 */
public class KaptchaTextCreator extends DefaultTextCreator
{
    private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");

    @Override
    public String getText()
    {
        Integer result = 0;
       // Random random = new Random();
        //int x = random.nextInt(10);
        int x =0;
        int y =0;
        int randomoperands = 0;
        StringBuilder suChinese = new StringBuilder();
        try {
            // 1. 初始化SecureRandom（密码学PRNG，符合文件“使用加密级PRNG”的建议）
            // 不指定算法时，系统自动选择安全算法（如SHA1PRNG、NativePRNG，熵值充足）
            SecureRandom secureRandom = SecureRandom.getInstanceStrong();
            // 2. 生成0-9的随机整数，功能与原代码一致
             x = secureRandom.nextInt(10);
             y = secureRandom.nextInt(10);
             randomoperands = secureRandom.nextInt(3);

            // （可选）若需固定算法（需确保环境支持），参考文件“SHA1PRNG”示例
            // SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            // secureRandom.nextBytes(new byte[16]); // 补充种子熵（文件建议“种子需充足熵”）

        } catch (NoSuchAlgorithmException e) {
            // 3. 异常处理（符合文件“Poor Error Handling”优化建议，不吞异常、记录日志）
            System.err.println("初始化SecureRandom失败，错误信息：" + e.getMessage());
            // 抛出业务异常，避免静默失败（文件建议“不忽略异常”）
            throw new RuntimeException("安全随机数生成器初始化异常", e);
        }


        if (randomoperands == 0)
        {
            result = x * y;
            suChinese.append(CNUMBERS[x]);
            suChinese.append("*");
            suChinese.append(CNUMBERS[y]);
        }
        else if (randomoperands == 1)
        {
            if ((x != 0) && y % x == 0)
            {
                result = y / x;
                suChinese.append(CNUMBERS[y]);
                suChinese.append("/");
                suChinese.append(CNUMBERS[x]);
            }
            else
            {
                result = x + y;
                suChinese.append(CNUMBERS[x]);
                suChinese.append("+");
                suChinese.append(CNUMBERS[y]);
            }
        }
        else
        {
            if (x >= y)
            {
                result = x - y;
                suChinese.append(CNUMBERS[x]);
                suChinese.append("-");
                suChinese.append(CNUMBERS[y]);
            }
            else
            {
                result = y - x;
                suChinese.append(CNUMBERS[y]);
                suChinese.append("-");
                suChinese.append(CNUMBERS[x]);
            }
        }
        suChinese.append("=?@" + result);
        return suChinese.toString();
    }
}
