#include "Shader.hpp"
#include "glew.h"

Shader::Shader(const char* sVertexSource, const char* sFragmentSource) {
  uVertexLocation = -1;
  uColorLocation = -1;

  uVertexShader = glCreateShader(GL_VERTEX_SHADER);
  uFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
  glShaderSource(uVertexShader, 1, (const GLchar**) &sVertexSource, NULL);
  glShaderSource(uFragmentShader, 1, (const GLchar**) &sFragmentSource, NULL);
  glCompileShader(uVertexShader);		

  int iVertexShaderCompileStatus;
  glGetShaderiv(uVertexShader, GL_COMPILE_STATUS, &iVertexShaderCompileStatus);

  if ((iVertexShaderCompileStatus) || (glIsShader(uVertexShader))) {
    //
  }
  else {
    return;
  }

  glCompileShader(uFragmentShader);

  int iFragmentShaderCompileStatus;
  glGetShaderiv(uFragmentShader, GL_COMPILE_STATUS, &iFragmentShaderCompileStatus);

  if ((iFragmentShaderCompileStatus) && (glIsShader(uFragmentShader))) {
    //
  }
  else {
    return;
  }

  uProgram = glCreateProgram();
  glAttachShader(uProgram, uVertexShader);
  glAttachShader(uProgram, uFragmentShader);

  glLinkProgram(uProgram);

  int iLinkedStatus;
  glGetProgramiv(uProgram, GL_LINK_STATUS, &iLinkedStatus);

  if ((iLinkedStatus) && (glIsProgram(uProgram))) {
    //
  }
  else {
    return;
  }
}

Shader::~Shader() {
  glDeleteProgram(uProgram);
  glDeleteShader(uVertexShader);
  glDeleteShader(uFragmentShader);
}

void Shader::Bind() const {
  glUseProgram(uProgram);
}

void Shader::Unbind() const {
  glUseProgram(0);
}

unsigned int Shader::GetAttribLocation(const char* sName) const {
  return glGetAttribLocation(uProgram, sName);
}

unsigned int Shader::GetUniformLocation(const char* sName) const {
  return glGetUniformLocation(uProgram, sName);
}

unsigned int Shader::GetVertexLocation() {
  if (uVertexLocation == -1) {
    uVertexLocation = GetAttribLocation("inPosition");
  }

  return uVertexLocation;
}

unsigned int Shader::GetColorLocation() {
  if (uColorLocation == -1) {
    uColorLocation = GetAttribLocation("inColor");
  }

  return uColorLocation;
}