package various;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletResponse;


/**
 * Kod klasy obiektu PhaseListenera realizującego generowanie 
 * danych binarnych (patrz rozdzial 4.4).
 *
 */
public class ImageOutputPhaseListener implements PhaseListener {
	
	private static final long serialVersionUID = 1L;
	private static final String BO_MAPPING = "/images";
	private static final String IMAGE_FORMAT = "jpeg";
	private static final String PARAM_ID = "text";

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

	public void afterPhase(PhaseEvent event) {
		FacesContext context = event.getFacesContext();
		ExternalContext externalContext = context.getExternalContext();
		if (!event.getFacesContext().getViewRoot().getViewId().startsWith(
				BO_MAPPING))
			return;
		HttpServletResponse servletResponse = (HttpServletResponse) externalContext
				.getResponse();

		String textToDisplay = externalContext.getRequestParameterMap().get(
				PARAM_ID);
		if (textToDisplay == null || "".equals(textToDisplay))
			textToDisplay = "Brak danych do renderowania";

		servletResponse.setContentType("image/" + IMAGE_FORMAT);
		try {
			OutputStream out = servletResponse.getOutputStream();
			// tu można umieścić dowolny kod generujący binarne dane
			BufferedImage img = new BufferedImage(400, 30,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics = (Graphics2D) img.getGraphics();
			graphics.drawString(textToDisplay, 5, 10);
			java.util.Iterator<ImageWriter> iter = ImageIO
					.getImageWritersByFormatName(IMAGE_FORMAT);
			ImageWriter writer = iter.next();
			writer.setOutput(ImageIO.createImageOutputStream(out));
			writer.write(img);
		} catch (IOException e) {
			throw new FacesException(e);
		}
		context.responseComplete();// kończy cykl przetwarzania
	}

	public void beforePhase(PhaseEvent arg0) {
	}
}
