#include "viewer.h"

#include <math.h>

Viewer::Viewer()
{
}

Viewer::~Viewer()
{
}

////////////////////////////////////////////////////////////////////////////////
// GL stuff

// initialize OpenGL context
void Viewer::init(int w, int h){
    _winWidth = w;
    _winHeight = h;

    // Couleur d'arrière plan
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_DEPTH_TEST);

    glViewport(0, 0, w, h);

    loadPrograms();
    createScene();


    // TODO initialiser la camera
}

void Viewer::reshape(int w, int h){
    _winWidth = w;
    _winHeight = h;
    glViewport(0, 0, w, h);
}

void Viewer::update(float time)
{
    // TODO Mise à jour de la scéne

    // Rendu de la scéne
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    _prog.activate();

    // TODO envoyer les uniforms
    _mesh.drawGeometry(_prog.id());

    glUseProgram(0);
}

void Viewer::loadPrograms()
{
    _prog.loadFromFiles(DATA_DIR"/shaders/simple.vert",
                        DATA_DIR"/shaders/simple.frag");

    checkError();
}

void Viewer::reloadPrograms()
{
    _prog.clear();
    _prog.loadFromFiles(DATA_DIR"/shaders/simple.vert",
                        DATA_DIR"/shaders/simple.frag");

    checkError();
}

void Viewer::createScene(void)
{
    _mesh.loadOBJ(DATA_DIR"/mesh/sphere.obj");
}

////////////////////////////////////////////////////////////////////////////////
// Events

/*!
   callback to manage mouse : called when user press or release mouse button
   You can change in this function the way the user 
   interact with the system.
 */
void Viewer::mousePressed(GLFWwindow *window, int button, int action)
{
}

 
/*!
   callback to manage mouse : called when user move mouse with button pressed
   You can change in this function the way the user 
   interact with the system.
 */
void Viewer::mouseMoved(int x, int y)
{
}

void Viewer::mouseScroll(double x, double y)
{
}


/*!
   callback to manage keyboard interactions
   You can change in this function the way the user 
   interact with the system.
 */
void Viewer::keyPressed(int key, int action, int mods)
{
    switch(key) {
    case GLFW_KEY_R:
        // Recharge les shaders
        if(action == GLFW_PRESS)
            reloadPrograms();
        break;
        //TODO Rajouter des contrôles
    default :
        break;
    }
}

void Viewer::charPressed(int key)
{
}
