/**
 * License Agreement.
 *
 *  JBoss RichFaces - Ajax4jsf Component Library
 *
 * Copyright (C) 2007  Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
package org.richfaces.realworld.servlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ajax4jsf.context.AjaxContext;
import org.jboss.seam.Component;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.domain.User;
import org.richfaces.realworld.fileupload.FileManager;
import org.richfaces.realworld.service.Constants;

public class PictureServlet extends javax.servlet.http.HttpServlet {


	public static final long serialVersionUID = 596009789004L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String fileName =  URLDecoder.decode(WebUtil.getFileName(request.getPathInfo()), "UTF8");
		if(!isAccessGranted(request, response, fileName)){
			sendToErrorPage(request, response);
			return;
		}
		byte[] data = getImageData(request, response, fileName);
		if(data == null){
			sendToErrorPage(request, response);
			return;
		}
		response.setContentType(Constants.IMAGE_JPG);
		response.setContentLength((int) data.length - 1);
		response.getOutputStream().write(data);
		response.getOutputStream().flush();
		response.getOutputStream().close();
	}

	private byte[] getImageData(HttpServletRequest request,
			HttpServletResponse response, String fileName) throws IOException {
		if (fileName == null) {
			return null;
		}
		FileManager fileManager = new FileManager();
		String uploadRoot = request.getSession().getServletContext().getInitParameter(Constants.UPLOAD_ROOT);
		fileManager.setUploadRoot(uploadRoot);
		File file = fileManager.getImage(fileName);
		InputStream paintData = null;
		byte[] data = new byte[(int) file.length() - 1];
		FileInputStream fileInputStream = null;
		BufferedInputStream bufferedInputStream = null;
		if (file != null) {
			try {
				fileInputStream = new FileInputStream(file);
				bufferedInputStream = new BufferedInputStream(fileInputStream);
				paintData = bufferedInputStream;
				paintData.read(data);
			} catch (FileNotFoundException e) {
				return null;
			} catch (IOException e) {
				return null;
			} finally {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					return null;
				}
				try {
					bufferedInputStream.close();
				} catch (IOException e) {
					return null;
				}
				try {
					paintData.close();
				} catch (IOException e) {
					return null;
				}
			}
		}
		return data;
	}

	private boolean isAccessGranted(HttpServletRequest request,
			HttpServletResponse response, String pathInfo) throws IOException {
		String userId = request.getParameter(Constants.USER_ID);
		EntityManager em = (EntityManager)Component.getInstance(Constants.ENTITY_MANAGER, true);
		User user = null;
		if(userId != null && !userId.equals("")){
			user = em.find(User.class, Long.valueOf(userId));
		}
		Image i = (Image)em.createQuery("from Image i where i.path=:path").setParameter(Constants.PATH_PARAMETER, pathInfo).getSingleResult();
		if(!i.getAlbum().isShared()){
			if(user != null){
				if(i.getAlbum().getOwner().equals(user) || user.getFriends().contains(i.getAlbum().getOwner())){
					//OK
				}else{
					return false;
				}
			}else{
				return false;
			}
		}
		return true;
	}

	private void sendToErrorPage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String contextPath = request.getContextPath();
		response.sendRedirect(contextPath + Constants.ERROR_PAGE);
		return;
	}
}
