package inc.monsters.mias.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PhotoServlet
 */
public class PhotoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static String imageDirectory;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PhotoServlet() {
		super();
	}

	@Override
	public void init() throws ServletException {
		super.init();
		setImageDirectory(getServletConfig().getInitParameter("imageDirectory"));
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String uri = request.getRequestURI();
		String fileName = imageDirectory + uri.substring(uri.lastIndexOf("/"));
//		String pathToFile = this.getServletContext().getRealPath(request.getPathInfo());
		File file = new File(fileName);

		getServletContext().log("Requested file: " + file.getAbsolutePath());

		// show a 404 page
		if (!file.exists() || !file.isFile()) {
			httpError(HttpServletResponse.SC_NOT_FOUND, response, "File not found: " + fileName);
		} else {
			try {
				streamImageFile(file, response);
			} catch (Exception e) {
				// Tell the user there was some internal server error.\
				// 500 - Internal server error.
				httpError(500, response, e.getMessage());
				e.printStackTrace();
			}
		}
	}

	private void streamImageFile(File file, HttpServletResponse response) {
		// find the right MIME type and set it as content type
		response.setContentType(new MimetypesFileTypeMap().getContentType(file));
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			response.setContentLength((int) file.length());

			// Use Buffered Stream for reading/writing.
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());

			byte[] buff = new byte[(int) file.length()];
			int bytesRead;

			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {

			throw new RuntimeException(e);
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
					// To late to do anything about it now, we may have already
					// sent some data to user.
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
					// To late to do anything about it now, we may have already
					// sent some data to user.
				}
			}
		}
	}

	private void httpError(int statusCode, HttpServletResponse response, String message) {
		try {
			response.sendError(statusCode, message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(Ht/promotions/some.jpgtpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	public static String getImageDirectory() {
		return imageDirectory;
	}

	public static void setImageDirectory(String imageDirectory) {
		PhotoServlet.imageDirectory = imageDirectory;
	}
}
