package page.image;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;

import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.core.WikiMap;
import org.wikiwebserver.handler.http.FormData;
import org.wikiwebserver.handler.http.HTTPHandler;
import org.wikiwebserver.handler.http.HTTPHeaders;
import org.wikiwebserver.handler.http.interfaces.*;

public class Counter implements HTTPResponder {
	
    public Object respond(HTTPHandler conn) throws IOException {
        
        String name = "default";
        int size = 25;
        
        // Obtain requested counter properties
        FormData formData = conn.getRequest().getFormData();
        if (formData != null) {
            String nameString = formData.getFirst("name");
            if (nameString != null) name = nameString;
            String sizeString = formData.getFirst("size");        
            if (sizeString != null) size = Integer.parseInt(sizeString);
        }
        if (size < 1 || size > 100) size = 25;        
        
        // Lookup counter name and increment count
        long count = getData().incrementLongValue(name + "Count", 1);
        Long startDate = (Long) getData().get(name + "StartDate");
        if (count == 0 || startDate == null) {
            startDate = new Long (System.currentTimeMillis());
            getData().put(name + "StartDate", startDate); 
        }       
        
        String countString = String.valueOf(count);
            
        String sinceString = "hits since";
                  
        String startDateString = HTTPHeaders.formatDate(startDate) + " ";
        
        String displayString = " " + countString + " " + sinceString + " " + startDateString + " ";
        
        // Figure out the size required to draw text
        Graphics2D g2d = new BufferedImage(1,1,BufferedImage.TYPE_INT_RGB).createGraphics();
        
        Font font = new Font(g2d.getFont().getName(), Font.BOLD, size);        
        
        FontMetrics fm = g2d.getFontMetrics(font);
        int width = fm.stringWidth(displayString);
        int height = fm.getHeight();
        
        // Render the text onto an image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        g2d = image.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);        
        g2d.setColor(Color.white);
        g2d.setFont(font);
        g2d.drawString(displayString, 0, fm.getAscent());

        return image;
    }
    
    public WikiMap getData() {
        WikiMap map = WareHouse.getWikiMap("Counter");
        if (map == null) map = WareHouse.initWikiMap("Counter");
        return map;        
    }      
}
