package org.richfaces.realworld.fileupload;

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.io.OutputStream;
import java.io.Serializable;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.domain.User;

@Name("avatarUpload")
@Scope(ScopeType.CONVERSATION)
public class AvatarUpload implements Serializable{
	
	@In(create=true)
	private FileManager fileManager;
	
	private FileItem avatarItem;
	
	private boolean autoUpload = false;
	
	public void avatarListener(UploadEvent event){
	    		UploadItem item = event.getUploadItem();
	    	    FileItem file = new FileItem();
	    	    file.setLength(item.getData().length);
	    	    Image image = new Image();
	    	    image.setName(item.getFileName());
	    	    file.setImage(image);
	    	    file.setData(item.getData());
	    	    this.setAvatarItem(file);
	}
	
	public synchronized void paintAvatar(OutputStream stream, Object object) throws IOException {
		stream.write(this.getAvatarItem().getData());
	}
	public boolean isAutoUpload() {
		return autoUpload;
	}

	public void setAutoUpload(boolean autoUpload) {
		this.autoUpload = autoUpload;
	}

	public FileItem getAvatarItem() {
		return avatarItem;
	}

	public void setAvatarItem(FileItem avatarItem) {
		this.avatarItem = avatarItem;
	}
}
