package page.example;

import java.io.*;
import java.net.Socket;

import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.handler.http.interfaces.*;
import page.config.SiteTemplatedPage;


public class TestRequestProcessing extends SiteTemplatedPage implements HTTPResponder {
	
    public void generate() {
        
        String request = "";
        boolean send = false;
        if (getFormData() != null) {
            request = getFormData().getFirst("request");
            send = true;
        }
        
        if (request == null || request.length() == 0) {
            request = getRequest().toString();
        }
        
        setTitle("Test request processing - Wikiwebserver.org");
        append("<h1>Test request processing</h1>");
        append("<p>This dynamic page allows you to send test HTTP requests to WikiWebServer.</p>");
        
        append("<h2>Request</h2>");
        append("<form name='req' method='post' action='" + getUrl() + "' charset='UTF-8'>");
        append("<p>Send the following request to WikiWebServer:</p>");                
        append("<textarea id='request' name='request' rows='14' cols='100' style='width: 100%' wrap='off'>");
        append(WareHouse.escapeHTMLEntities(request));
        append("</textarea>");
        
        append("<input class='submit' type='submit' name='action' value='Send'/>");
        append("</form>");

        if (send) {
            append("<h2>Response:</h2>");
            append("<p>The following header was returned from WikiWebServer:</p>");
            append("<textarea id='content' name='content' rows='14' cols='100' style='width: 100%' wrap='off'>");  
            String res;
            try {
                res = simulateRequest(request);
            } catch (IOException ex) {
                res = "WikiWebServer did not respond as expected. (" +
                      ex.getMessage() + ")";
                ex.printStackTrace();
            }
            append(WareHouse.escapeHTMLEntities(res));
            append("</textarea>");              
        }
    }
    
    private String simulateRequest(String req) throws IOException {
        if (!req.endsWith("\r\n\r\n")) {
            req += "\r\n\r\n";
        }
        Socket s = new Socket("127.0.0.1", 8080);
        s.setSoTimeout(1000);
        OutputStream out = s.getOutputStream();
        out.write((req).getBytes());
        out.flush();
        
        StringBuilder res = new StringBuilder();
        
        InputStream in = s.getInputStream();
        int i = in.read();
        while (i > -1) {
            res.append((char)i);
            if (res.lastIndexOf("\r\n\r\n") > -1) break;
            i = in.read();
        }
        in.close();
        return res.toString();
    }
    
    public String getCacheKey() {
        return null;
    }    
}
