package org.richfaces.realworld.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.core.Events;
import org.jboss.seam.security.Identity;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.manager.FileManager;
import org.richfaces.realworld.service.Constants;

@Name("directLink")
@Scope(ScopeType.SESSION)
@AutoCreate
//TODO nick - session-scoped bean depending on request parameters? i'm in doubts...
public class DirectLinkHelper {
	@In(value="entityManager")
	protected EntityManager em;
	@In(create = true)
	FileManager fileManager;
	@RequestParameter
	protected Long imageId;
	
	@In Identity identity;
	
	private Long id;
	
	private static final String IMAGE_DIRECT_LINK = "/includes/directImage.seam?imageId=";
	
	private static String imageDirectLinkPrefix;

	public synchronized void paintImage(OutputStream out, Object data)
			throws IOException {
		Image im = em.find(Image.class, id);
		//TODO nick - '&&' so only admins can see their own unshared images?
		if(im.getAlbum().getShelf().isShared() || (identity.hasRole("admin") && im.getAlbum().getOwner().getLogin().equals(identity.getUsername()))){
			//TODO nick - copy-pasted 99% from ImageLoader
			File imageResource = fileManager.getImage(im.getPath());
			if (imageResource != null) {
				FileInputStream fileInputStream = new FileInputStream(imageResource);
				BufferedInputStream bufferedInputStream = new BufferedInputStream(
						fileInputStream);
				InputStream paintData = bufferedInputStream;
				if (null == paintData) {
					Events.instance().raiseEvent(Constants.ADD_ERROR_EVENT,
							new Exception(""));
					return;
				}
				try {
					BufferedImage images = ImageIO.read(paintData);
					ImageIO.write(images, Constants.JPEG, out);
				} catch (Exception e) {
					Events.instance().raiseEvent(Constants.ADD_ERROR_EVENT,
							new Exception(""));
					return;
				} finally {
					fileInputStream.close();
					bufferedInputStream.close();
					paintData.close();
				}
			}
		}else{
			return;
		}
	}
	
	 public void start(){
		 id=imageId;
	 }
	 
	 public String getDirectImageLink(Image image) {
			if (imageDirectLinkPrefix == null) {
				FacesContext context = FacesContext.getCurrentInstance();
				if (context == null) {
					return null;
				}
				ExternalContext extc = context.getExternalContext();
				if (extc == null) {
					return null;
				}
				
				//TODO nick - see org.ajax4jsf.renderkit.RendererUtils#encodeResourceURL(TemplateContext, Object)
				Object request = extc.getRequest();
				
				if (request instanceof HttpServletRequest) {
					HttpServletRequest servletRequest = (HttpServletRequest)request;
					String contextPath = servletRequest.getContextPath();
					StringBuffer url = servletRequest.getRequestURL();
					int i = url.indexOf(contextPath);
					if (i > 0) {
						imageDirectLinkPrefix = url.substring(0, i) + contextPath + IMAGE_DIRECT_LINK;
					}
				}
			}
			return imageDirectLinkPrefix + image.getId();
		}
}