/**
 * 
         -------- Copyright (C) [2012]  [Kristofer SCHWEIGER & Niklas FLORIAN1]---------

    This program is free software; you can redistribute it and/or modify it under the terms of the
 *  GNU General Public License as published by the Free Software Foundation; either version 2 of the License,
 *  or (at your option) any later version.
    This program 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 General Public License for more details.
 * 
    You should have received a copy of the GNU General Public License along with this program; if not, 
 *  write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA

 * 
 * For any licensing issues please contact us under following adress: Mosaik.Projekt.2012@gmail.com
 */


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{
		
		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;
	}
	
}
