package com.xrtb.bidder;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * A class that handles server side includes for the RTBServer web server.
 * @author Ben M. Faul
 *
 */

public class SSI {
	
	static final String PREAMBLE = "<!--#include virtual=\"";
	public static String convert(String page) throws Exception {

		if (page.indexOf(PREAMBLE) != -1) { // don't allocate resources when it is not needed.
			StringBuilder sb = new StringBuilder(page);
			while(getTagValues(sb));

			page = sb.toString();
		}

		return page;
	}
	
	/**
	 * Pluck the code between <% and %>, execute it, then take the result and replace the old text.
	 * @param buf StringBuffer. The html page.
	 * @return boolean. True if a tag was found, otherwise false.
	 * @throws Exception on JavaScript language errors or unbalanced <% %> tags.
	 */
	private static boolean getTagValues(StringBuilder buf) throws Exception {
		int start = buf.indexOf(PREAMBLE);
		int stop = buf.indexOf("-->",start);
		if (start < 0 || stop < 0)
			return false;

		String code = new String(buf.substring(start + PREAMBLE.length(), stop));
		//Object o = engine.eval(code);
		//if (o == null)
		//	o = "";
		//else if (o instanceof String)
		//	o = o.toString();
		//else
		//	o = "";
		
		int tail = code.indexOf("\"");
		code = code.substring(0, tail);
		if (code.startsWith("www") == false) {
			code = "www/" + code;
		}
		
		String inner  = null;
		try {
			
			inner = Charset
				.defaultCharset()
				.decode(ByteBuffer.wrap(Files.readAllBytes(Paths
						.get(code)))).toString();

			buf.replace(start, stop + 3, inner);
		} catch(Exception error) {
			error.printStackTrace();
			return false;
		}
		if (start != 0 && buf.length() < start + 1) {
			if (buf.charAt(start) == '\n' && buf.charAt(start - 1) == '\n')
				buf.replace(start - 1, start + 1, "\n");
		}

		return true;
	}

}

@@ -269,16 +269,24 @@
 SI %7B%0A%09%0A%09
+private 
 static f
@@ -409,23 +409,24 @@
 f (page.
-indexOf
+contains
 (PREAMBL
@@ -431,14 +431,8 @@
 BLE)
- != -1
 ) %7B 
@@ -821,86 +821,8 @@
 se.%0A
-%09 * @throws Exception on JavaScript language errors or unbalanced %3C%25 %25%3E tags.%0A
 %09 */
@@ -877,33 +877,16 @@
 der buf)
- throws Exception
  %7B%0A%09%09int
@@ -1083,153 +1083,8 @@
 ));%0A
-%09%09//Object o = engine.eval(code);%0A%09%09//if (o == null)%0A%09%09//%09o = %22%22;%0A%09%09//else if (o instanceof String)%0A%09%09//%09o = o.toString();%0A%09%09//else%0A%09%09//%09o = %22%22;%0A
 %09%09%0A%09
@@ -1155,16 +1155,17 @@
 ;%0A%09%09if (
+!
 code.sta
@@ -1182,17 +1182,8 @@
 ww%22)
- == false
 ) %7B%0A

Clean up source code removing unnecessary assigns.