package theGhastModding.midiPlayerGL.renderer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL30;

import theGhastModding.midiPlayerGL.models.Loader;
import theGhastModding.midiPlayerGL.text.FontType;
import theGhastModding.midiPlayerGL.text.GUIText;
import theGhastModding.midiPlayerGL.text.TextMeshData;

public class TextMasterRenderer {
	
	private Loader loader;
	private Map<FontType, List<GUIText>> texts = new HashMap<FontType, List<GUIText>>();
	private TextRenderer renderer;
	
	public TextMasterRenderer(Loader loader) {
		renderer = new TextRenderer();
		this.loader = loader;
	}
	
	public void render(){
		renderer.render(texts);
	}
	
	public void loadText(GUIText text) {
		FontType font = text.getFont();
		TextMeshData data = font.loadText(text);
		int[] d = loader.loadToVAO(data.getVertexPositions(), data.getTextureCoords());
		text.setMeshInfo(d[0], data.getVertexCount(), new int[] {d[1], d[2]});
		List<GUIText> textBatch = texts.get(font);
		if(textBatch == null){
			textBatch = new ArrayList<GUIText>();
			texts.put(font, textBatch);
		}
		textBatch.add(text);
	}
	
	public void removeText(GUIText text, boolean removeFromMemory){
		List<GUIText> textBatch = texts.get(text.getFont());
		textBatch.remove(text);
		if(textBatch.isEmpty()){
			texts.remove(text.getFont());
		}
		if(removeFromMemory){
			GL30.glDeleteVertexArrays(text.getMesh());
			for(int vbo:text.getVBOs()) {
				GL15.glDeleteBuffers(vbo);
			}
		}
	}
	
	public void cleanUp(){
		renderer.cleanUp();
	}
	
}