package electrosphere.renderer.ui.widgets;

import electrosphere.main.Globals;
import electrosphere.renderer.Material;
import electrosphere.renderer.Model;
import electrosphere.renderer.framebuffer.Framebuffer;
import electrosphere.renderer.framebuffer.FramebufferUtils;
import electrosphere.renderer.texture.Texture;
import electrosphere.renderer.ui.Widget;
import org.joml.Vector3f;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER;
import static org.lwjgl.opengl.GL30.glBindFramebuffer;

/**
 *
 * @author amaterasu
 */
public class ImagePanel extends Widget {
    
    Material customMat = new Material();
    Texture texture = null;
    
    
    Vector3f texPosition = new Vector3f(0,0,0);
    Vector3f texScale = new Vector3f(1,1,0);
    
    public ImagePanel(int x, int y, int width, int height){
        texture = Globals.assetManager.fetchTexture("Textures/default_diffuse.png");
        customMat.setTexturePointer(texture.getTexturePointer());
        this.positionX = x;
        this.positionY = y;
        this.width = width;
        this.height = height;
    }
    
    public void setTexture(Texture texture){
        customMat.setTexturePointer(texture.getTexturePointer());
    }
    
    public Texture getTexture(){
        return texture;
    }
    
    

    @Override
    public void draw(int parentFramebufferPointer, int parentWidth, int parentHeight) {
        //this call binds the screen as the "texture" we're rendering to
        //have to call before actually rendering
        glBindFramebuffer(GL_FRAMEBUFFER, parentFramebufferPointer);
        
        float ndcX = (float)positionX/parentWidth;
        float ndcY = (float)positionY/parentHeight;
        float ndcWidth = (float)width/parentWidth;
        float ndcHeight = (float)height/parentHeight;
        
        Vector3f boxPosition = new Vector3f(ndcX,ndcY,0);
        Vector3f boxDimensions = new Vector3f(ndcWidth,ndcHeight,0);
        
        Model planeModel = Globals.assetManager.fetchModel(Globals.planeModelID);
        planeModel.pushUniformToMesh("plane", "mPosition", boxPosition);
        planeModel.pushUniformToMesh("plane", "mDimension", boxDimensions);
        planeModel.pushUniformToMesh("plane", "tPosition", texPosition);
        planeModel.pushUniformToMesh("plane", "tDimension", texScale);
        planeModel.meshes.get(0).setMaterial(customMat);
        planeModel.drawUI();
    }
    
}
