<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC 
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%
/*
Copyright (C) 2006 - 2007 Martin Slota
 
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
 
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
%>
<%@ page
contentType="text/html; charset=UTF-8"
import="java.io.*"
import="java.util.Date"
import="java.text.SimpleDateFormat"
import="java.util.List"
import="java.util.Iterator"

import="javax.servlet.ServletContext"

import="org.apache.commons.fileupload.FileItemFactory"
import="org.apache.commons.fileupload.disk.DiskFileItemFactory"
import="org.apache.commons.fileupload.FileItem"
import="org.apache.commons.fileupload.servlet.ServletFileUpload"


import="lp.ui.ConfigManager"
import="lp.ui.DlpWebappHelper"
%>
<%!
ServletContext context;
ConfigManager appConfig;

String writeChecked(boolean isChecked) {
	return isChecked ? " checked=\"checked\"" : "";
}

void makeAbsolutePath(String key) {
	String path = appConfig.getProperty(key);
	File f = new File(path);
	if (!f.isAbsolute())
		path = context.getRealPath(path);
	appConfig.setProperty(key, path);
}

%>
<%
context = pageContext.getServletContext();
appConfig = new ConfigManager();
appConfig.loadFromXML(application.getResourceAsStream("/webapp.properties"));
makeAbsolutePath("location.lparse");
makeAbsolutePath("location.smodels");
String pathPrefix = appConfig.getProperty("path.prefix");
%>
<html lang="en" xml:lang="en">
	
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="Pragma" content="no-cache" />
		<meta http-equiv="Cache-Control" content="no-cache" />
		<link rel="stylesheet" type="text/css" href="<%= pathPrefix %>style.css" />
		<title>Implementation of Refined dynamic stable models</title>
		<meta name="description" content="A web application for computing the 
		refined dynamic stable models of a dynamic logic program." />
	</head>
	
	<body>
		<div id="container">
			<h1>Implementation of dynamic logic programs</h1>
			<p><strong>version: 1.0_beta1</strong></p>
			<p>
				This implementation of the refined semantics for 
				<abbr title="Dynamic Logic Programs">DLPs</abbr> is a by-product
				of my attempts to implement
				<abbr title="Evolving Logic Programs">EVOLP</abbr> with variable
				support. You can find more about EVOLP and its implementation
				on the
				<a 
					class="external"
					title="Martin Slota's master's thesis"
					href="http://slotik.medovnicek.sk/2006/thesis/">
					home page of my master's thesis
				</a>.
			</p>
			
			<%
			boolean showDlp = false;
			boolean showGroundedDlp = false;
			boolean showTransformedDlp = false;
			boolean showModels = true;
			Reader inputReader = null;
			String directInput = null;
			
			if (ServletFileUpload.isMultipartContent(request)) {
				// reset these values and set them only in case their checkbox was checked
				showDlp = false;
				showGroundedDlp = false;
				showTransformedDlp = false;
				showModels = false;
				// Create a factory for disk-based file items
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setRepository(new File("/tmp"));
				// Create a new file upload handler
				ServletFileUpload upload = new ServletFileUpload(factory);
				// Parse the request
				List items = upload.parseRequest(request);
				//Process the uploaded items
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) {
						String name = item.getFieldName();
						String value = item.getString();
						if (name.equals("maxModels")) {
							try {
								int maxModelsFromField = Integer.parseInt(value);
								appConfig.setProperty("maxModels", Integer.toString(maxModelsFromField));
							} catch (NumberFormatException e) {
								// leave the previous value...
							}
						} else if (name.equals("showDlp")) {
							showDlp = true;
						} else if (name.equals("showGroundedDlp")) {
							showGroundedDlp = true;
						} else if (name.equals("showTransformedDlp")) {
							showTransformedDlp = true;
						} else if (name.equals("showModels")) {
							showModels = true;
						} else if (name.equals("directInput")) {
							directInput = DlpWebappHelper.escapeXMLSpecials(value);
							if (inputReader == null)
								inputReader = new StringReader(value);
						}
					} else {
						if (item.getFieldName().equals("fileInput") && item.getSize() > 0) {
							InputStream inputStream = item.getInputStream();
							inputReader = new InputStreamReader(inputStream);
						}
					}
				}
				
				if (inputReader != null) {
					out.println("<h2>Results</h2>");
					DlpWebappHelper helper = new DlpWebappHelper(appConfig, out);
					helper.setInput(inputReader);
					if (showDlp) {
						out.println("<h3>Input program</h3>");
						helper.writeDlp();
					}
					if (!helper.isError() && showGroundedDlp) {
						out.println("<h3>Grounded input program</h3>");
						helper.writeGroundedDlp();
					}
					if (!helper.isError() && showTransformedDlp) {
						out.println("<h3>Transformed program</h3>");
						helper.writeTransformedDlp();
					}
					if (!helper.isError() && showModels) {
						out.println("<h3>Refined Dynamic stable models</h3>");
						helper.writeModels();
					}
				}
			}
			
			int maxModels;
			try {
				maxModels = Integer.parseInt(appConfig.getProperty("maxModels"));
			} catch (NumberFormatException e) {
				maxModels = 0;
			}
			
			if (directInput == null) {
				directInput = DlpWebappHelper.escapeXMLSpecials(
						"not fly(X) <- animal(X).\n" +
						"\nnewProgram.\n\n" +
						"fly(X) <- bird(X).\n" +
						"\nnewProgram.\n\n" +
						"not fly(X) <- penguin(X).\n" +
						"\nnewProgram.\n\n" +
						"animal(X) <- bird(X).\n" +
						"bird(X) <- penguin(X).\n" +
						"animal(pluto).\n" +
						"bird(duffy).\n" +
						"penguin(tweety).");
			}
			%>
			
			<h2>Form for entering a Dynamic logic program</h2>
			<form method="post" enctype="multipart/form-data" action="">
				<fieldset>
					<legend>General options</legend>
					<p>
						<label for="maxModels">Maximum number of computed models:</label>
						<input type="text" name="maxModels" id="maxModels" value="<%= maxModels %>" size="5" />
					</p>
					<p>
						<input type="checkbox" name="showDlp" id="showDlp" value=""<%= writeChecked(showDlp) %> />
						<label for="showDlp">Show the parsed input program</label>
						<br />
						<input type="checkbox" name="showGroundedDlp" id="showGroundedDlp" value=""<%= writeChecked(showGroundedDlp) %> />
						<label for="showGroundedDlp">Show the grounded input program</label>
						<br />
						<input type="checkbox" name="showTransformedDlp" id="showTransformedDlp" value=""<%= writeChecked(showTransformedDlp) %> />
						<label for="showTransformedDlp">Show the transformed input program</label>
						<br />
						<input type="checkbox" name="showModels" id="showModels" value=""<%= writeChecked(showModels) %> />
						<label for="showModels">Show dynamic stable models</label>
						<br />
					</p>
				</fieldset>
				<fieldset>
					<legend>Input by file upload</legend>
					<p>
						<label for="fileInput" title="Choose a local UTF-8 encoded file with a Dynamic logic program. Programs should be separated by a &quot;newProgram.&quot; fact.">Choose a local file with a DLP</label>
						<br />
						<input type="file" id="fileInput" name="fileInput" size="50" value="" />
					</p>
					<input type="submit" value="Compute models" />
				</fieldset>
				<fieldset>
					<legend>Direct input</legend>
					<p>
						<label for="directInput" title="Paste the dynamic logic program here. Programs should be separated by a &quot;newProgram.&quot; fact.">Paste the DLP here:</label>
						<br />
						<textarea id="directInput" name="directInput" rows="20" cols="80"><%= directInput %></textarea>
					</p>
					<input type="submit" value="Compute models" />
				</fieldset>
			</form>
			
			<%
			String reqURL = request.getRequestURL().toString();
			SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm");
			String lastUpdated = df.format(new Date(new File(
					context.getRealPath("index.jsp")).lastModified()));
			%>
			
			<div id="footer">
				<p class="validation">
					<a href="http://validator.w3.org/check?uri=referer"><img
							src="<%= pathPrefix %>images/valid-xhtml10.png" height="31" width="88"
						alt="Valid XHTML 1.0!" /></a>
					<a href="http://jigsaw.w3.org/css-validator/check/referer"><img
							src="<%= pathPrefix %>images/vcss.png" height="31" width="88"
						alt="Valid CSS!" /></a>
				</p>
				<p>Last updated: <%= lastUpdated %></p>
				<p>URL: <%= reqURL %></p>
				<p>Home URL: http://slotik.medovnicek.sk/</p>
				<p>Copyleft (&cent;) 2006 - 2007 Martin Slota</p>
			</div>
		</div>
	</body>
	
</html>