/**
 * 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.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 java.io.Serializable;

import javax.imageio.ImageIO;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.core.Events;
import org.richfaces.realworld.manager.FileManager;
import org.richfaces.realworld.service.Constants;

@Name("imageLoader")
@Scope(ScopeType.CONVERSATION)
//TODO nick - why is this conversation-scoped?
public class ImageLoader implements Serializable {

    private static final long serialVersionUID = -1572789608594870285L;

    @In
    FileManager fileManager;
    @In("#{messages['file_processing_error']}")
    private String FILE_PROCESSING_ERROR;

    //TODO nick - synchronized would make this a bottleneck, especially considering that this method
    //			  consumes plenty of CPU time
    public synchronized void paintImage(OutputStream out, Object data) throws IOException {
        if (null == data) {
            return;
        }
        File imageResource = fileManager.getImage(data.toString());
        if (imageResource != null) {
            FileInputStream fileInputStream = new FileInputStream(imageResource);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            InputStream paintData = bufferedInputStream;
            //TODO nick - paintData is never null
            if (null == paintData) {
                Events.instance().raiseEvent(Constants.ADD_ERROR_EVENT, new Exception(FILE_PROCESSING_ERROR));
                return;
            }
            try {
                //TODO nick - pass-through writing will save us large amount of CPU time and images quality
            	BufferedImage images = ImageIO.read(paintData);
                ImageIO.write(images, Constants.JPEG, out);
            } catch (Exception e) {
                //TODO nick - any particular reason to catch not to take the whole method body into try/catch? 
            	//TODO nick - how useful is new Exception(...)? why not use just String?
            	Events.instance().raiseEvent(Constants.ADD_ERROR_EVENT, new Exception(FILE_PROCESSING_ERROR));
                //TODO nick - that's not necessary at all
            	return;
            } finally {
            	//TODO nick - calling bufferedInputStream.close() is enough
                fileInputStream.close();
                bufferedInputStream.close();
                paintData.close();
            }
        }
    }

    //TODO nick - this is copy-pasted 99% from paintImage()
    public synchronized void paintImageFromFile(OutputStream out, Object data) throws IOException {
        if (null == data) {
            return;
        }
        File imageResource = fileManager.getImageFile(data.toString());
        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(FILE_PROCESSING_ERROR));
                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(FILE_PROCESSING_ERROR));
                return;
            } finally {
                fileInputStream.close();
                bufferedInputStream.close();
                paintData.close();
            }
        }
    }
}
