#include "lines_renderer.h"

#include "engine.h"
#include "android/log.h"

#define TAG "LuaLines"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)

static GLfloat maxLineWidth = 1.0f;

void LinesRenderer::init() {
  GLfloat lineWidthRange[2] = {0.0f, 0.0f};
  glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, lineWidthRange);
  LOGD("Maximum line width for this GPU: %f", lineWidthRange[1]);
  maxLineWidth = lineWidthRange[1] - 1.0f;
}

const GLfloat color[] = {1.0, 1.0, 1.0, 1.0f};

void LinesRenderer::draw(std::vector<glm::vec3> &positions, const std::vector<int>& indices) {
  glUseProgram(RawShader::get());
  glLineWidth(maxLineWidth);

  GLint vColorLocation = glGetUniformLocation(RawShader::get(), "vColor");
  glUniform4fv(vColorLocation, 1, color);

  float points[indices.size() * 3];
  int j = 0;
  for (int indice : indices) {
    points[j] = positions[indice].x;
    j++;
    points[j] = positions[indice].y;
    j++;
    points[j] = positions[indice].z;
    j++;
  }

  glVertexAttribPointer(DefaultShader::vPositionAttrIndex, 3, GL_FLOAT, false,
                        COORDS_PER_VERTEX * sizeof(GLfloat),
                        points);
  glEnableVertexAttribArray(DefaultShader::vPositionAttrIndex);

  glDrawArrays(GL_LINES, 0, indices.size());
}

