package dataBase;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

import javax.imageio.ImageIO;

import mosaik.MosaikConstants;


/**
 * LRU Buffer/Cache for images.
 * Watch out for memory consumption with large images!!!
 * 
 * @author Kristofer Schweiger
 */
public class PictureBuffer {
	
	public static int bufferSize = 20;
	private LinkedList<PictureBufferElement> buffer = new LinkedList<PictureBufferElement>();
	
	public PictureBuffer(){
		//buffer = new DataList<PictureBufferElement>(bufferSize, comp);
		//buffer.tolerance = bufferTolerance;
	}
	
	public BufferedImage getPicture(File f) throws IOException{
		
		MosaikConstants.pictureLoad.start();
		BufferedImage image;
		
		// --- try A: find image ---
		//
		image = getPicturefromBuffer(f);
		if(image!=null)
			return image;		// found in buffer!
		
		// --- or B: load image ---
		//
		image     = ImageIO.read(f);					// do not sync for IO-Operation!!!
		PictureBufferElement el = new PictureBufferElement(image, f);
		BufferedImage imageTmp;
		
		synchronized(this){
			
			imageTmp = getPicturefromBuffer(f);
			if(imageTmp!=null)
				return imageTmp;		// do not add a second time!
			
			buffer.addFirst(el);
			//Out.pl(">> Loaded pic '"+el.file.getName()+"'");
			
			while(buffer.size() > bufferSize)
				buffer.removeLast();
			
			return image;
		}
		
	}
	
	/**
	 * Get picture from Buffer only
	 * @param f
	 * @return
	 * @throws IOException
	 */
	public synchronized BufferedImage getPicturefromBuffer(File f) throws IOException {
		
		Iterator<PictureBufferElement> it = buffer.iterator();
		while(it.hasNext()){

			PictureBufferElement el = it.next();
			//Out.pl(">> Iterate...");

			if(el.file.equals(f)){

				//Out.pl(">> Found pic '"+el.file.getName()+"'");
				it.remove();
				buffer.addFirst(el);
				return el.image;
			}
		}

		return null;
	}
	
}
