package page.example;

import org.wikiwebserver.handler.http.HTTPException;
import org.wikiwebserver.handler.http.interfaces.HTTPResponder;
import org.wikiwebserver.util.VelocityEnforcement;
import org.wikiwebserver.util.VelocityExceededException;

import page.config.SiteTemplatedPage;

import static org.wikiwebserver.html.HTMLHelper.*;

public class VelocityEnforcementTestPage extends SiteTemplatedPage implements HTTPResponder {
	
    public void generate() throws HTTPException {
    	
    	String type = "velocity_enforcement_test_page_ips"; 
    	String ip = getHandler().getSourceAddress();    	
    	int limit = 5;
    	long period = 20 * 1000;
    	long wait = 2 * 60 * 1000;
    	
        setTitle("Velocity Enforcement Test - WikiWebServer.org");  
        
        append(h(1, "Velocity Enforcement Test"));
        append(p("This page enforces only 5 page requests are handled " +
        		 " in the space of 20 seconds from the same IP address.")); 
        append(p("If this velocity is exceeded, a 2 minute penalty is applied." +
		 		 " Requests in the last 20 seconds of penalty period" +
		 		 " results in an additional 2 minute penalty."));
    	
    	try {
    		VelocityEnforcement.enforceVelocity(type, ip, limit, period, wait);
    		append(h(2, "Velocity OK"));
    		append(p("...doing some work..."));
    	}
    	catch (VelocityExceededException ex) {
    		append(h(2, "Velocity exceeded"));
    		append(p("...do not pass go, do not collect 200 pounds..."));
    		
    		long waitMillis = VelocityEnforcement.getWaitTimeUntilAcceptableVelocity(type, ip, period, limit);
    		append(p("Please wait " + waitMillis/1000 + " seconds..."));
    	}
    }
 
    @Override
    public String getCacheKey() {
    	// Make sure the response is not cached.
    	return null;
    }
}
