package zall;

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

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

import org.apache.commons.fileupload.util.Streams;

import zall.bean.Image;
import zall.bean.Media;
import zall.bean.User;
import zall.bean.Video;
import zutil.db.DBConnection;
import zutil.io.file.FileUtil;

public class ZalleryContent extends HttpServlet{
	private static final long serialVersionUID = 1L;

	public  void doGet(HttpServletRequest request, HttpServletResponse  response) throws ServletException{
		DBConnection db = null;
		try {
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			String size = request.getParameter("size");
			if( size == null ) size = "";

			if( user != null || size.equalsIgnoreCase("small") ){
				db = Zallery.getDB();
				Media media;
				
				if( "video".equals(request.getParameter("type")) )
					media = Video.load(db, Integer.parseInt(request.getParameter("id")));
				else
					media = Image.load(db, Integer.parseInt(request.getParameter("id")));

				if( media != null ){
					File file = null;
					if( size.equalsIgnoreCase( "small" ) )
						file = media.getFile( Media.Size.SMALL );
					else if( size.equalsIgnoreCase( "medium" ) )
						file = media.getFile( Media.Size.MEDIUM );
					else if( size.equalsIgnoreCase( "large" ) )
						file = media.getFile( Media.Size.LARGE );
					else
						file = media.getFile( Media.Size.ORIGINAL );
					
					if( request.getParameter("download") != null )
						response.setHeader("Content-disposition", "attachment; filename="+media.getTitle()+"."+FileUtil.getFileExtension(file));
					
					if( file.exists() ){
						if( "video".equals(request.getParameter("type")) )
							response.setContentType("video/"+FileUtil.getFileExtension(file));
						else
							response.setContentType("image/"+FileUtil.getFileExtension(file));
						response.setContentLength( (int)file.length() );
						
						BufferedInputStream in = new BufferedInputStream( new FileInputStream(file) );
						Streams.copy(in, response.getOutputStream(), false);
						in.close();
					}
					else
						response.setStatus( 404 );
				}
				else{
					// Page not found
					response.setStatus( 404 );
				}
				
			}
			else{
				// Unauthorized
				response.setStatus( 401 );
			}

		} catch (Exception e) {
			throw new ServletException(e);
		} finally{
			if(db != null) db.close();
		}
	}
}
