#include "Axis.hpp"
#include "ShaderCodes.hpp"
#include "glew.h"

Axis::Axis(int iOrientation, QString sText) {
  iType = AXIS;
  this->iOrientation = iOrientation;
  this->sText = sText;

  vHorizontalVertices = new glm::vec4[2];
  vHorizontalVertices[0] = glm::vec4(ORIGIN_X, ORIGIN_Y, 0.0f, 1.0f);
  vHorizontalVertices[1] = glm::vec4(UPPER_X, ORIGIN_Y, 0.0f, 1.0f);

  vVerticalVertices = new glm::vec4[2];
  vVerticalVertices[0] = glm::vec4(ORIGIN_X, UPPER_Y, 0.0f, 1.0f);
  vVerticalVertices[1] = glm::vec4(ORIGIN_X, ORIGIN_Y, 0.0f, 1.0f);

  vColors = new glm::vec4[2];
  vColors[0] = glm::vec4(AXIS_COLOR, AXIS_COLOR, AXIS_COLOR, 1.0f);
  vColors[1] = glm::vec4(AXIS_COLOR, AXIS_COLOR, AXIS_COLOR, 1.0f);

  vIndices = new int[2];
  vIndices[0] = 0;
  vIndices[1] = 1;

  pShader = new Shader(sSolidColorVertSource, sSolidColorFragSource);

  if (iOrientation == ORIENTATION_VERTICAL) {
      pLabel = new Label(sText, FONTSTYLE_ELEMENT, VERTICAL_AXIS_TEXT_OFFSET,
        (1.0f - ((UPPER_Y - ORIGIN_Y) / 2.0f + ORIGIN_Y + 1.0f) / 2.0f) * HEIGHT,
        ORIENTATION_VERTICAL, Qt::AlignCenter);
  }
  else {
    pLabel = NULL;
  }
}

Axis::~Axis() {
  delete vHorizontalVertices;
  delete vVerticalVertices;
  delete vColors;
  delete vIndices;
  delete pShader;

  if (pLabel != NULL) {
    delete pLabel;
  }
}

int Axis::GetOrientation() {
  return iOrientation;
}

QString Axis::GetText() {
  return sText;
}

void Axis::Draw(QPainter* pPainter) {
  pPainter->setRenderHint(QPainter::Antialiasing);
  glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
  glLineWidth(AXIS_WIDTH);

  pShader->Bind();

  glEnableVertexAttribArray(pShader->GetVertexLocation());

  if (iOrientation == ORIENTATION_VERTICAL) {
    glVertexAttribPointer(pShader->GetVertexLocation(), 4, GL_FLOAT, GL_FALSE, 0, vVerticalVertices);
  }
  else {
    glVertexAttribPointer(pShader->GetVertexLocation(), 4, GL_FLOAT, GL_FALSE, 0, vHorizontalVertices);
  }

  glEnableVertexAttribArray(pShader->GetColorLocation());
  glVertexAttribPointer(pShader->GetColorLocation(), 4, GL_FLOAT, GL_FALSE, 0, vColors);

  glDrawElements(GL_LINES, 2, GL_UNSIGNED_INT, vIndices);

  pShader->Unbind();

  glLineWidth(1.0f);
  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}

void Axis::DrawLabels(QPainter* pPainter) {
  if (pLabel != NULL) {
    pLabel->Draw(pPainter);
  }
}

void Axis::ChangePosition(float fDeltaLeft, float fDeltaTop, float fDeltaBottom) {
  UNREFERENCED(fDeltaLeft);
  UNREFERENCED(fDeltaTop);
  UNREFERENCED(fDeltaBottom);
}

void Axis::ChangeAlpha(float fDeltaAlpha) {
  for (int i = 0; i < 2; i++) {
    vColors[i] = vColors[i] + glm::vec4(0.0f, 0.0f, 0.0f, fDeltaAlpha);
  }

  if (pLabel != NULL) {
    pLabel->ChangeAlpha(fDeltaAlpha);
  }
}