package de.frajul.endlessroll.entities.textures;

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

import java.io.InputStream;

import de.frajul.endlessroll.main.GameLog;

/**
 * Created by Julian on 26.11.2015.
 */
public class TextureLoader {

    private Context context;

    public TextureLoader(Context context) {
        this.context = context;
    }

    public int loadTextureId(int texture, boolean isAtlas) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), texture);
        return loadTextureId(bitmap, isAtlas);
    }

    public Texture loadTexture(String inAssetsLocation) throws Exception {
        InputStream is = context.getAssets().open(inAssetsLocation);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
        return new Texture(loadTextureId(bitmap, false), 1, 1);
    }

    private int loadTextureId(Bitmap bitmap, boolean isAtlas) {
        int id = genTexture();

        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, id);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,
                GLES20.GL_NEAREST);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER,
                GLES20.GL_NEAREST);

        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

        bitmap.recycle();
        GameLog.d("Texture " + id + " successfully loaded");
        return id;
    }

    private int genTexture() {
        int[] idField = new int[1];
        GLES20.glGenTextures(1, idField, 0);
        return idField[0];
    }

}
