package com.diagbot.util;

import com.diagbot.entity.ImageCaptchaParams;
import org.patchca.color.SingleColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory;
import org.patchca.font.RandomFontFactory;
import org.patchca.service.Captcha;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.word.RandomWordFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author huangrusheng
 * @version 1.0
 * @date 2021/5/20 9:54
 */
public class ImageCaptchaUtil {
    private String text;

    /**
     * 以Web的img识别的base64返回
     * @param
     * @return 图片文字内容+base64格式的img标签识别的图片
     * @throws IOException
     */
    public BufferedImage createRandom() throws IOException{
        ImageCaptchaParams params = new ImageCaptchaParams();
        ConfigurableCaptchaService  captchaService = new ConfigurableCaptchaService();
        captchaService.setColorFactory(new SingleColorFactory(Color.black));
        CurvesRippleFilterFactory curvesRippleFilterFactory = new CurvesRippleFilterFactory();
        curvesRippleFilterFactory.setColorFactory(captchaService.getColorFactory());
        curvesRippleFilterFactory.setStrokeMin(1);
        curvesRippleFilterFactory.setStrokeMax(1.5f);
        captchaService.setFilterFactory(curvesRippleFilterFactory);
        captchaService.setHeight(params.getHeight());
        captchaService.setWidth(params.getWidth());
        RandomWordFactory wordFactory = new RandomWordFactory();
        wordFactory.setCharacters(params.getWords());
        wordFactory.setMaxLength(params.getMaxWordAmount());
        wordFactory.setMinLength(params.getMinWordAmount());
        captchaService.setWordFactory(wordFactory);
        RandomFontFactory fontFactory = new RandomFontFactory();
        fontFactory.setMaxSize(params.getMaxFontSize());
        fontFactory.setMinSize(params.getMinFontSize());
        captchaService.setFontFactory(fontFactory);
        Captcha captcha = captchaService.getCaptcha();
        this.text = captcha.getChallenge();
        return captcha.getImage();
    }

    /**
     * 获取验证码文本的方法
     */
    public String getText() {
        return text;
    }
}
