package jp.sf.amateras.mirage.example.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.sf.amateras.mirage.SqlManager;
import jp.sf.amateras.mirage.example.entity.Book;
import jp.sf.amateras.mirage.session.SessionFactory;

public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String id = req.getParameter("id");
		if(id == null || id.length() == 0){
			throw new RuntimeException("Book id is not specified.");
		}

		SqlManager sqlManager = SessionFactory.getSession().getSqlManager();
		Book book = sqlManager.findEntity(Book.class, new Long(id));
		if(book == null){
			throw new RuntimeException("Book does not exist.");
		}
		if(book.getImageName() == null || book.getImageName().length() == 0){
			throw new RuntimeException("Image is not attached.");
		}

		resp.setContentType(getContentType(book.getImageName()));
		ServletOutputStream out = resp.getOutputStream();
		out.write(book.getImage());
	}

	private static String getContentType(String fileName){
		int index = fileName.lastIndexOf('.');

		if(index >= 0){
			String extension = fileName.substring(index + 1).toLowerCase();
			if(extension.equals("jpeg") || extension.equals("jpg")){
				return "image/jpeg";
			} else if(extension.equals("gif")){
				return "image/gif";
			} else if(extension.equals("png")){
				return "image/png";
			} else if(extension.equals("bmp")){
				return "image/bmp";
			}
		}

		throw new RuntimeException("Image filename is invalid.");
	}
}
