package ca.uvic.gild.servlet;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.ParserDelegator;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;


/** 
 * @author  Adrian, Rob Lintern
 */
public class GildContentPresenterServlet extends HttpServlet {

	/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
	 * @param request servlet request
	 * @param response servlet response
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("GildContentPresenterServlet.processRequest...");
		if (!(request.getServerName().equals("localhost") || request.getServerName().equals("127.0.0.1"))) {
			try {
				response.getOutputStream().println("Sorry, you can only access this Gild servlet through the local host!");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return;
		}
		String filePathRelativeToProjectRoot = request.getParameter("file");
		String projectName = request.getParameter("project");
		System.out.println("projectName: " + projectName);
		System.out.println("filePathRelativeToProjectRoot: " + filePathRelativeToProjectRoot);
		boolean success = false;
		
		//System.out.println("server = " + request.getServerName() + ":" + request.getServerPort());
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		try {
			if ((projectName != null) && (projectName.length() > 0)) {
				// file path relative to the project
				IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();
				IProject myProject = workSpaceRoot.getProject(projectName);
	
				if (myProject != null) {
					org.eclipse.core.resources.IFile eclipseFile = myProject.getFile(filePathRelativeToProjectRoot);
					if (eclipseFile != null && eclipseFile.exists()) {
						
						String absFilePath = eclipseFile.getLocation().toString();					
						java.io.File file = new java.io.File (absFilePath);
						if (file.exists()) {
							try {
								FileReader in = new FileReader(file);
								if (file.getName().toLowerCase().endsWith("html") || file.getName().toLowerCase().endsWith("htm")) {
									//if this is a html file then we want to parse it and add javacripts etc
									response.setContentType("text/html");
									HtmlParser parser = new HtmlParser(out);
									//parser.filePathRelativeToProjectRoot(filePathRelativeToProjectRoot);
									//parser.setProjectName(projectName);
									IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
									IProject project = root.getProject(projectName);
									if (project != null && project.exists()) {
										IResource fileToParse = project.findMember(filePathRelativeToProjectRoot);
										if (fileToParse != null && fileToParse.exists() && IResource.FILE == fileToParse.getType()) {
											parser.setParseFile((IFile)fileToParse);
											parser.setHost(request.getServerName() + ":" + request.getServerPort());
											(new ParserDelegator ()).parse(in, parser, true);
										}
									}
								} else {
									// just copy the whole file from in to out
									response.setContentType("text/plain");
									int c;
									while ((c = in.read()) != -1) {
										out.write(c);
									}
								}
								
								
								success = true;
							} catch (FileNotFoundException e1) {
								e1.printStackTrace();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
					}
				}
			}
			
			if (!success) {
				out.println("<h3>Error - Could not find file in the </h3>");
				out.println("&nbsp;&nbsp;&nbsp; project = '" + (projectName != null ? projectName : "(not given)") + "'<br>");	
				out.println("&nbsp;&nbsp;&nbsp; file = '" + (filePathRelativeToProjectRoot != null ? filePathRelativeToProjectRoot : "(not given)") + "'");	
			}
		} catch (Exception e) {
			e.printStackTrace(out);
		} finally {
			out.close();
		}
		

	}

	/** Handles the HTTP <code>GET</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
		processRequest(request, response);
	}

	/** Handles the HTTP <code>POST</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
		processRequest(request, response);
	}

	/** 
	 * Returns a short description of the servlet.
	 */
	public String getServletInfo() {
		return "Presents HTML content with additional tags and javascript to invoke Gild's active HTML";
	}

}
