package speiger.src.coreengine.rendering.shader;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;

import org.lwjgl.system.MemoryUtil;

public class ShaderCache {
	public static final ShaderCache INSTANCE = new ShaderCache();
	private Path cache;
	
	public void init(Path cache) {
		this.cache = cache;
		if(Files.notExists(cache)) {
			try { Files.createDirectories(cache); }
			catch(IOException e) { 
				e.printStackTrace(); 
				this.cache = null;
			}
		}
	}
	
	public boolean hasCache() {
		return cache != null;
	}
	
	public ByteBuffer readFromCache(String location, FileTime latestSource) {
		try { return readFromCacheUnsafe(location, latestSource); }
		catch(Exception e) { e.printStackTrace(); }
		return null;
	}
	
	private ByteBuffer readFromCacheUnsafe(String location, FileTime latestSource) throws IOException {
		if(cache == null) return null;
		Path path = cache.resolve(location+".bin");
		if(Files.exists(path)) {
			if(Files.getLastModifiedTime(path).compareTo(latestSource) <= 0) return null;
			byte[] data = Files.readAllBytes(path);
			return MemoryUtil.memAlloc(data.length).put(data).flip();
		}
		return null;
	}
	
	public void storeInCache(String location, byte[] data) {
		if(cache == null) return;
		try { Files.write(cache.resolve(location+".bin"), data); }
		catch(Exception e) {
			e.printStackTrace();
		}
	}
}
