package speiger.src.coreengine.rendering.textures.simple;

import org.lwjgl.stb.STBImage;
import org.lwjgl.system.MemoryUtil;

import speiger.src.coreengine.assets.base.IAssetProvider;
import speiger.src.coreengine.rendering.textures.base.BaseTexture;
import speiger.src.coreengine.rendering.textures.base.TextureMetadata;
import speiger.src.coreengine.rendering.utils.GLFunctions;

public class DirectTexture extends BaseTexture {
	int width;
	int height;
	long imageData;
	TextureMetadata metadata;
	
	public DirectTexture(int width, int height, long imageData, TextureMetadata metadata) {
		this.width = width;
		this.height = height;
		this.imageData = imageData;
		this.metadata = metadata;
		track();
	}
	
	@Override
	public void load(IAssetProvider provider) {
		loadTexture();
	}
		
	@Override
	public void delete(boolean untrack) {
		super.delete(untrack);
		if(imageData == 0L || !untrack) return;
		if(metadata.isSTBData()) {
			STBImage.nstbi_image_free(imageData);
			imageData = 0L;
		}
		else {
			MemoryUtil.nmemFree(imageData);
			imageData = 0;
		}
	}
	
	@Override
	public int width() { return width; }
	@Override
	public int height() { return width; }
	
	private void loadTexture() {
		createTexture();
		metadata.applyArguments(id());
		GLFunctions.upload2DImage(id(), 0, metadata, width, height, 0, imageData);
		if(metadata.generateMipMappings()) GLFunctions.generateMipMaps(textureType());
	}
}
