package charactermanaj.graphics.io;

import java.awt.image.BufferedImage;
import java.io.IOException;

import charactermanaj.graphics.ImageCache;


public class ImageCachedLoader extends ImageLoaderImpl {

	/**
	 * リソースに対するイメージキャッシュ.<br>
	 * リソースは複数のプロファイルで共有しえるのでstaticとしている。
	 */
	private static ImageCache<ImageResourceCacheKey> caches = new ImageCache<ImageResourceCacheKey>();
	
	public BufferedImage load(ImageResource imageResource) throws IOException {
		if (imageResource == null) {
			throw new IllegalArgumentException();
		}

		ImageResourceCacheKey key = new ImageResourceCacheKey(imageResource);

		synchronized (caches) {
			BufferedImage img = caches.get(key);
			if (img == null) {
				img = super.load(imageResource);
				caches.set(key, img);
				caches.unlockImages(); // 即時解放許可
			}
			return img;
		}
	}
}

final class ImageResourceCacheKey {

	private final ImageResource imageResource;
	
	private final long lastModified;
	
	private final int hashCode;
	
	public ImageResourceCacheKey(ImageResource imageResource) {
		if (imageResource == null) {
			throw new IllegalArgumentException();
		}
		this.imageResource = imageResource;
		this.lastModified = imageResource.lastModified();
		this.hashCode = imageResource.hashCode() ^ (int) this.lastModified;
	}
	
	@Override
	public int hashCode() {
		return this.hashCode;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		if (obj != null && obj instanceof ImageResourceCacheKey) {
			ImageResourceCacheKey other = (ImageResourceCacheKey) obj;
			return lastModified == other.lastModified
					&& imageResource.equals(other.imageResource);
		}
		return false;
	}
}
