package dataBase;

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

import javax.imageio.ImageIO;

import util.simpleIO.Out;

import dataBase.search.DataList;

/**
 * LRU Buffer/Cache for images.
 * 
 * @author Kristofer Schweiger
 *
 */
public class PictureBuffer {
	
	public static int bufferSize = 40;
	private LinkedList<PictureBufferElement> buffer = new LinkedList<PictureBufferElement>();
	
	public PictureBuffer(){
		//buffer = new DataList<PictureBufferElement>(bufferSize, comp);
		//buffer.tolerance = bufferTolerance;
	}
	
	public synchronized BufferedImage getPicture(File f) throws IOException{
		
		// --- try A: find image ---
		//
		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;
			}
		}
		
		// --- or B: load image ---
		//
		BufferedImage image     = ImageIO.read(f);
		PictureBufferElement el = new PictureBufferElement(image, f);
		buffer.addFirst(el);
		Out.pl(">> Loaded pic '"+el.file.getName()+"'");
		
		while(buffer.size() > bufferSize)
			buffer.removeLast();
		
		return image;
	}
	
}
