package org.hirw.game;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;

import lombok.Getter;

public class TexturedMesh extends Mesh {
  @Getter private Texture[] textures;

  private final int TEXTURE_COORDS_SIZE = 2;

  public TexturedMesh(Shader shader, Texture[] textures, float[] vertexArray, int[] elementArray) {
    super(shader, vertexArray, elementArray);
    this.textures = textures;
  }

  public TexturedMesh(Shader shader, Texture[] textures) {
    this(shader, textures, DEFAULT_VERTEX_ARRAY, DEFAULT_ELEMENT_ARRAY);
  }

  protected int initialiseAttribPointers() {
    int vertexSizeInBytes = super.initialiseAttribPointers();

    int offset = (POSITION_SIZE + RGBA_SIZE) * FLOAT_SIZE_IN_BYTES;
    glVertexAttribPointer(2, TEXTURE_COORDS_SIZE, GL_FLOAT, false, vertexSizeInBytes, offset);
    glEnableVertexAttribArray(2);

    return vertexSizeInBytes;
  }

  protected int calculateVertexSizeInBytes() {
    return (POSITION_SIZE + RGBA_SIZE + TEXTURE_COORDS_SIZE) * FLOAT_SIZE_IN_BYTES;
  }

  protected void glDraw() {
    for (int i = 0; i < textures.length; i++) {
      int textureUnitIndexStart = GL_TEXTURE0;
      int textureUnitIndex = textureUnitIndexStart + i;
      glActiveTexture(textureUnitIndex);
      glBindTexture(GL_TEXTURE_2D, getTextures()[i].getTextureID());
      String uniformName = "texture" + Integer.toString(i + 1);
      glUniform1i(glGetUniformLocation(getShader().getShaderProgramID(), uniformName), i);
    }
    super.glDraw();
  }
}
