package com.ejweb.modules.front.report.servlet;


import com.ejweb.modules.front.report.utils.CaptchaUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;

/**
 * Created by BrianHolsen on 2017-08-08 at 11:42.
 */
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = 1325598241;

    private int height = 25;
    private int width = 90;

    public CaptchaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        String ch = CaptchaUtil.getCaptcha(request.getParameter("code"));
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Max-Age", 0);
        Random r = new Random(new Date().getTime());
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = image.createGraphics();
        graphics2D.setColor(new Color(192, 192, 192)); // or the background color u want
        graphics2D.fillRect(0, 0, width, height);
        for (int i = 0; i < 20; i++) {
            Line2D line1 = new Line2D.Float(Math.abs(r.nextInt()) % width, Math.abs(r.nextInt()) % height
                    , Math.abs(r.nextInt()) % width, Math.abs(r.nextInt()) % height);
            graphics2D.setPaint(new GradientPaint(30, 30, new Color(Math.abs(r.nextInt())), 15, 25, new Color(Math.abs(r.nextInt()))));
            graphics2D.draw(line1);
        }
        graphics2D.setPaint(new GradientPaint(30, 30, Color.BLUE, 15, 25, Color.RED, true));
        Font font = new Font("Verdana", Font.CENTER_BASELINE, 20);
        graphics2D.setFont(font);
        graphics2D.drawString(ch, 5, 20);
        graphics2D.dispose();
        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpeg", outputStream);
        outputStream.close();
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
