/**
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 *
 * Copyright (C)
 * <a href="http://www.inab.org">Spanish National Institute of Bioinformatics (INB)</a>
 * <a href="http://www.bsc.es">Barcelona Supercomputing Center (BSC)</a>
 * <a href="http://inb.bsc.es">Computational Node 6</a>
 */

package org.inb.swing;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import javax.imageio.ImageIO;

/**
 * Auxiliary class for loading images with a simple soft reference based cache.
 * 
 * @author Dmitry Repchevsky
 */

public final class ImageLoader
{
    private static ConcurrentHashMap<String, SoftReference<Image>> images = new ConcurrentHashMap<String, SoftReference<Image>>();

    private ImageLoader() {}

    public static Image load(String path)
    {
        SoftReference<Image> ref = images.get(path);

        Image image;
        if (ref != null)
        {
            image = ref.get();

            if (image != null)
            {
                return image;
            }
        }

        image = read(path);

        if (image != null)
        {
            images.put(path, new SoftReference<Image>(image));
        }

        return image;
    }

    public static BufferedImage read(String path)
    {
        InputStream in = ImageLoader.class.getClassLoader().getResourceAsStream(path);

        if (in != null)
        {
            try
            {
                return ImageIO.read(new BufferedInputStream(in));
            }
            catch(IOException ex)
            {
                ex.printStackTrace();
            }
        }

        return null;
    }
}