package xaero.rotatenjump.game.graphics;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;

/**
 * Created by xaero on 21/08/2017.
 */

public class Texture {

    private int glTexture;
    private Bitmap bitmap;
    private boolean uploaded = false;
    private int filter;

    public Texture(Context context, int resourceID) {
        this(context, resourceID, GLES20.GL_NEAREST);
    }

    public Texture(Bitmap image){
        this(image, GLES20.GL_NEAREST);
    }

    public Texture(Context context, int resourceID, int filter){
        this(BitmapFactory.decodeResource(context.getResources(), resourceID), filter);
    }

    public Texture(Bitmap image, int filter){
        this.bitmap = image;
        this.filter = filter;
    }

    private void upload(){
        final int[] textureLocations = new int[1];
        GLES20.glGenTextures(1, textureLocations, 0);
        glTexture = textureLocations[0];
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, glTexture);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, filter);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, filter);
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
        bitmap.recycle();
        bitmap = null;
        uploaded = true;
    }

    public void bindTexture(){
        if(!uploaded)
            upload();
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, glTexture);
    }

    public static void unbindTexture(){
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, -1);
    }

}
