package com.philisense.www.api.generator.impl;

import com.philisense.www.api.generator.VcodeGenerator;
import com.philisense.www.dto.ImageCode;
import org.patchca.background.SingleColorBackgroundFactory;
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 org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.*;

/**
 * 图形验证码生成
 */
public class ImageCodeGenerator implements VcodeGenerator {

    @Override
    public ImageCode generate(ServletWebRequest request) {

        // todo 暂时写死默认值，后面放到属性配置中
        int width = ServletRequestUtils.getIntParameter(request.getRequest(), "width", 180);
        int height = ServletRequestUtils.getIntParameter(request.getRequest(), "height", 60);
        int length = ServletRequestUtils.getIntParameter(request.getRequest(), "length", 4);
        int size = ServletRequestUtils.getIntParameter(request.getRequest(), "size", 42);

        ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
        cs.setBackgroundFactory(new SingleColorBackgroundFactory(new Color(251, 232, 231)));
        cs.setColorFactory(new SingleColorFactory(new Color(0, 120, 215)));
        cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
        RandomWordFactory rwf = new RandomWordFactory();
        rwf.setMinLength(length);
        rwf.setMaxLength(length);
        cs.setWordFactory(rwf);
        RandomFontFactory rff = new RandomFontFactory();
        rff.setMinSize(size);
        rff.setMaxSize(size);
        cs.setFontFactory(rff);
        cs.setWidth(width);
        cs.setHeight(height);

        Captcha captcha = cs.getCaptcha();

        return new ImageCode(captcha.getImage(), captcha.getChallenge());
    }
}
