package edu.neu.ccs.demeterf.http;

import edu.neu.ccs.demeterf.http.server.*;
import edu.neu.ccs.demeterf.http.classes.*;
import edu.neu.ccs.demeterf.lib.*;
import java.io.*;

/** Test Server response class */
@Server
public class Test{
    @Port
    static int PORT = 9000;
    @MaxMessageSize
    static final int MAX = 20;
    
    @Path("/html")
    public HTTPResp htmlResp(HTTPReq req)
    { return HTTPResp.htmlResponse("<html>\n"+
            "<head><title>Sample Page</title></head>\n"+
            "<body><b>HELLO</b> <i>There</i></body><html>"); }
    
    @Path("/text")
    public HTTPResp textResp(HTTPReq req)
    { return HTTPResp.textResponse("Plain Text Response"); }
    
    @Path("/urlargs")
    public HTTPResp urlResp(HTTPReq req)
    { return mapToHTML(req.urlArgs()); }

    @Path("/headers")
    public HTTPResp headerResp(HTTPReq req)
    { return mapToHTML(req.getHeaders()); }
    
    HTTPResp mapToHTML(Map<String,String> m){
        return HTTPResp.htmlResponse("<html>"+
                m.toList().fold(new List.Fold<Entry<String,String>, String>(){
                    public String fold(Entry<String,String> e, String r){
                        return "<b>"+e.getKey()+"</b> : <i>"+e.getVal()+"</i><br/>"+r;
                    }
                }, "</html>"));
    }
    
    @Path
    public HTTPResp fileResp(HTTPReq req){
        String file = req.getHead().getUrl().trimArgs();
        if(!file.startsWith("/file/"))
            return HTTPResp.textError("ERROR: Unknown Request");
        file = file.substring(file.indexOf('/',1));
        try{
            BufferedReader buff = new BufferedReader(new FileReader(file));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while((line = buff.readLine()) != null)
                sb.append(line).append('\n');
            return HTTPResp.textResponse(sb.toString());
        }catch(IOException e){
            return HTTPResp.error("FileNotFound: \'"+file+"\'");
        }
    }
    
    @ExceptionHandler
    public HTTPResp exception(){
        return HTTPResp.error("Exception: ");
    }
    
    static void p(String s){ System.err.print(s); }
    public static void main(String[] args) throws Exception{
        try{
            p("Starting Server\n");
            Factory.setVerbose(true);
            if(args.length == 1)
                PORT = Integer.parseInt(args[0]);
            ServerThread server = Factory.create(new Test());
            p("Hit enter to shutdown");
            System.in.read();
            server.shutdown();
        }catch(RequestException e){
            System.out.println("Error: "+e.getMessage());
        }
    }
}