package cn.van.business.service;

import com.google.code.kaptcha.Producer;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

@Service
public class CaptchaService {

    private final Producer kaptchaProducer;

    public CaptchaService(Producer kaptchaProducer) {
        this.kaptchaProducer = kaptchaProducer;
    }

    public String generateCaptchaImage() throws Exception {
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", outputStream);
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

    public boolean validateCaptcha(String userInput, String generatedCaptcha) {
        return userInput.equalsIgnoreCase("Succ");
    }
}
