package quant.rich.emoney.controller.common;

import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import quant.rich.emoney.service.AuthService;
import quant.rich.emoney.util.ArithmeticCaptchaGen;
import quant.rich.emoney.util.ArithmeticCaptchaGen.Captcha;

@RestController
@RequestMapping("/captcha")
public class KaptchaController extends BaseController {

    @Autowired
    DefaultKaptcha kaptcha;
    @GetMapping(value = "/get", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getCaptcha() throws Exception {
        
        Captcha captcha = ArithmeticCaptchaGen.generate();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        session.setAttribute(AuthService.CAPTCHA, captcha.answer());
        ImageIO.write(kaptcha.createImage(captcha.expr()), "jpg", os);
        byte[] result = os.toByteArray();
        os.close();
        return result;
    }
}
