/*
 * Created on Jan 3, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.prolixtech.jaminid_examples.ajax;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import com.prolixtech.jaminid.ContentOracle;
import com.prolixtech.jaminid.Daemon;
import com.prolixtech.jaminid.Protocol;
import com.prolixtech.jaminid.Request;
import com.prolixtech.jaminid.Response;

/**
 * @author Constantinos Michael
 *
 */
public class SimpleAjaxServer extends ContentOracle {

    public static final int PORT = 8080;
    

    private static final String ROOT_PATH = "src/com/prolixtech/jaminid_examples/ajax/resources/";
    private static final String DEFAULT = "index.html";
    
    private Random rand = new Random();
    
    volatile private static Daemon daemon;
    
    
    private String root_canonical;
    public SimpleAjaxServer(){
        
        File root_p = new File(ROOT_PATH);
        if(!root_p.exists()) {
            throw new IllegalArgumentException("ROOT PATH CAN'T BE FOUND: " + ROOT_PATH);
        }
        try{
            root_canonical = root_p.getCanonicalPath();
        } catch (Exception e) {
            throw new IllegalArgumentException("IO ERROR WITH: " + ROOT_PATH);
        }
    }
    
    public String demultiplex(Request connRequest, Response connResponse) {
    	HashMap<String,String> outputHash=new HashMap<String,String>();
    	System.out.println(connRequest.getLocation());
    	
    	
    	if(connRequest.getLocation().equals("/runsim.html") ){
    		String strat = connRequest.getParamOrNull("strategy");
    		double d = Double.parseDouble(connRequest.getParam("start"));
    		long startDate = new java.util.Date(connRequest.getParam("sday")+"-" + connRequest.getParam("smon") + "-" + connRequest.getParam("syear")).getTime();
			long endDate = new java.util.Date(connRequest.getParam("eday")+"-" + connRequest.getParam("emon") + "-" + connRequest.getParam("eyear")).getTime();
			String ticker = connRequest.getParam("ticker");
    		if(strat==null){
    			String msg = "<p>Running simulator on symbol <B>" + ticker + 
    				"</B> with an initial investment of <B>$" + dcf.format(d) + "</B>" +
    				" from <B>" + (new Date(startDate)).toString() + "</B> to <B>" + (new Date(endDate)).toString() + "</B></p>";  
    			
    			outputHash.put("RUNSIMDETS", msg);
    		} else {
//    			strategy=InsiderTrading&start=10000&ticker=IBM&sday=1&smon=Jan&syear=1985&eday=1&emon=Jan&eyear=2005
    			
				
	    			
					String mxa = "showtrans.html?strategy="+strat+"&start="+d+"&sdate="+startDate+"&edate="+endDate+"&ticker="+ticker;
	    			try {
						Thread.sleep(1000 + rand.nextInt(5000));
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					double v = rand.nextDouble() * 2 * d;
	    			
	    			String cl = (v-d>=0 ? "greentext" : "redtext");
	    			
	    			StringBuffer a = new 	    			StringBuffer();
	    			a.append(strat);
	    			a.append("|");
	    			a.append("<h1> RandomStrategy </h1>");
	    			a.append("<p>Balance: ");
	    			a.append(dcf.format(v));
	    			a.append("<br/>");
	    			a.append("% Change: ");
	    			a.append("<span class='"+cl+"'>");
	    			a.append(dcf.format((v-d)/d * 100));
	    			a.append("</span>");
	    			a.append("</p>");
	    			
	    			a.append("<p><a href="+mxa+">Number of transactions: ");
	    			a.append(rand.nextInt(100));
	    			a.append("</a></p>");
	    			System.out.println(a.toString());
	    			return a.toString();
					
				
    			
    			
//    			long endDate = new java.util.Date("15-Oct-2005").getTime();
    			
    			

    			
    		}
    		
    	}
    	
    	
    	
    	String loc = connRequest.getLocation();
        if(loc.equals("/")) loc = DEFAULT;
        File x = new File(ROOT_PATH + loc);
        
        
        try {
            x = x.getCanonicalFile();
            if(! (x.getAbsolutePath().startsWith(root_canonical))) throw new IOException("Not within filesystem limits");
            if(x.getName().endsWith("html") || x.getName().endsWith("htm")) {
            	StringBuffer a = new StringBuffer();
            	BufferedReader br = new BufferedReader(new FileReader (x));
            	while(true){
            		String line = br.readLine();
            		if(line==null)
            			break;
            		a.append(line);
            		a.append("\n");
            		
            	}
            	br.close();
            	fillInTemplate(a,connRequest,connResponse, outputHash);
        		return a.toString();
            	
            } else {
            	connResponse.sendFile(x);
            }
        } catch (IOException e) {
            connResponse.setStatus(Protocol.NOT_FOUND);
        } catch (Exception e){
            connResponse.setStatus(Protocol.INTERNAL_SERVER_ERROR);
        }
        return "";
        
                
    }
    
    
    
    private void fillInTemplate(StringBuffer a, Request connRequest, Response connResponse, HashMap<String, String> outputHash) {
		while(true){
			int s = a.indexOf("%%-%");
			if(s<0)
				break;
			int e = a.indexOf("%-%%", s);
			String key = a.substring(s+4, e);
			if(outputHash.containsKey(key)){
				a.replace(s, e+4, outputHash.get(key));
			} else {
				a.replace(s, e+4, getFiller(key, connRequest, connResponse));
			}
				
			
			
		}
		
	}

	private String getFiller(String string, Request connRequest, Response connResponse) {
		System.out.println("Getting " + string);
		if(string.equals("ENVLOC")){
			return "" + connRequest.getLocation() + "?" + connRequest.getParamString();
		}
				// TODO Auto-generated method stub
		return "N/A";
	}

	DecimalFormat dcf = new DecimalFormat();
	
	


	public static void main(String[] args) {
        
        SimpleAjaxServer s = new SimpleAjaxServer();
        daemon = new Daemon(PORT, s);
        System.out.println("The webserver is now running! Visit http://localhost:" + PORT + " through your favorite web browser.");
         
    }
    
}
