package httpserver;

import java.io.RandomAccessFile;
import java.io.IOException;
import java.io.OutputStream;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;

public class ImageCountHandler extends BaseHandler
    implements HttpRequestHandler
{
    public ImageCountHandler() { }

    private static String nocache =
      "Cache-control: no-cache\nCache-control: no-store\nPragma: no-cache\nExpires: 0\n";

    private int count = 0;

    private int nextCount() {
	return count++;
    }

    private void writePNGImageString(
	int imgWidth, int imgHeight, String str, OutputStream out )
	throws IOException
    {
        BufferedImage image =
	    new BufferedImage( imgWidth, imgHeight,
	    BufferedImage.TYPE_4BYTE_ABGR);
	Graphics2D g2d = image.createGraphics(); 
	Font f = new Font( "Monospaced", Font.BOLD, 14 );
	g2d.setFont( f );
	FontMetrics fm = g2d.getFontMetrics();
	g2d.setColor( Color.white );
	g2d.fillRect(0, 0, imgWidth, imgHeight );
	g2d.setColor( Color.red );

	Rectangle2D bounds = fm.getStringBounds( str, g2d );
	int w = (int)bounds.getWidth();
	int h = (int)bounds.getHeight();
	int x = (imgWidth - w)/2;
	int y = imgHeight - (imgHeight - h)/2;
	g2d.drawString( str, x, y );

	ImageIO.write(image, "png", out );
    }

    public void handleRequest(
        HttpRequest request,
	HttpResponse response ) throws Exception
    {
        String method = request.getMethod();
	String path = request.getPath();
	log( method + " " + path );
        if ( !method.equals("GET") && !method.equals("POST") ) {
            String msg = "only handle GET and POST";
            log( msg );
	    response.sendError(HttpResponse.RESP_METHOD_NOT_ALLOWED, msg);
            return;
        }
	if ( path.equals( "/no" ) ) {
	    response.setHeaders( nocache.getBytes() );
	}
	response.setContentType("image/png");
	String c = nextCount() + "";
	try {
	    writePNGImageString(
		70, 20, c, response.getOutputStream());
	}
	catch( IOException ex ) {
	    //XXX fix me
	}
    }
}
