package siprp.images.servlet;

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 siprp.database.cayenne.objects.Image;
import siprp.database.cayenne.providers.ImageDAO;

public final class ImagesServlet extends HttpServlet
{
	private static final long serialVersionUID = 999506147931075031L;
	private static final double MAX_WIDTH = 4.5;
	private static final double MAX_HEIGHT = 2.0;
	
	private static final String PARAMETER_ID = "id";

	public void doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException
	{
		response.setContentType( "image/png" );
		ServletOutputStream out = response.getOutputStream();
		String param = request.getParameter( PARAMETER_ID );
		System.out.println(param);
		try
		{
			Integer id = new Integer(param);
			Image img = new ImageDAO().getImageForID( id );
//			int width = img.getWidth( null );
//			int height = img.getHeight( null );
//			double wrel = ((double)width ) / MAX_WIDTH;
//			double hrel = ((double)height ) / MAX_HEIGHT;
//			if( wrel > 1 && wrel > hrel )
//			{
//				img = img.getScaledInstance( MAX_WIDTH, -1, Image.SCALE_FAST );
//			}
//			else if( hrel > 1 && hrel > wrel )
//			{
//				img = img.getScaledInstance( -1, MAX_HEIGHT, Image.SCALE_FAST );
//			}
			out.write( img.getImageData() );
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
