
//
// Code from https://learnopengl.com/Getting-started/Hello-Triangle
//


#include <glad/glad.h>
#include <GLFW/glfw3.h>

#include <iostream>
#include <cmath>
#include <fstream>
#include <sstream>
#include <glm/glm.hpp>
#include <vector>
#include <tiny_obj_loader.h>
#include <glm/ext.hpp>

void readFile(std::string const &filepath, std::string &content);
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
void loadOBJ(std::string const &assetPath, std::vector<glm::vec3> &vertices, std::vector<GLuint> &indices);

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

unsigned int cur_width = SCR_WIDTH;
unsigned int cur_height = SCR_HEIGHT;

int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // build and compile our shader program
    // ------------------------------------
    // vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    std::string vShaderCode;
    readFile("../../0x-teapot/shader/triangle.vert", vShaderCode);
    const GLchar * vCode = vShaderCode.c_str();
    glShaderSource(vertexShader, 1, &vCode, NULL);
    glCompileShader(vertexShader);
    // check for shader compile errors
    int success;
    char infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    std::string fShaderCode;
    readFile("../../0x-teapot/shader/triangle.frag", fShaderCode);
    const GLchar * fCode = fShaderCode.c_str();
    glShaderSource(fragmentShader, 1, &fCode, NULL);
    glCompileShader(fragmentShader);
    // check for shader compile errors
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // link shaders
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    // check for linking errors
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    std::vector<glm::vec3> vertices;
    std::vector<GLuint> indices;

    loadOBJ("../../0x-teapot/obj/Teapot.obj", vertices, indices);

    unsigned int EBO, VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
    // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);

	//indices
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(GLuint), &indices[0], GL_STATIC_DRAW);

	glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));

    // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
    // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
    // glBindVertexArray(0);


    // bind the VAO (it was already bound, but just to demonstrate): seeing as we only have a single VAO we can
    // just bind it beforehand before rendering the respective triangle; this is another approach.
    glBindVertexArray(VAO);

	glEnable(GL_DEPTH_TEST);


    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // input
        // -----
        processInput(window);

        // render
        // ------
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // be sure to activate the shader before any calls to glUniform
        glUseProgram(shaderProgram);

        glm::mat4 model = glm::mat4(1.0f);
        glm::mat4 projection = glm::perspective(glm::radians(45.0f), cur_width/(float)cur_height, 0.1f, 100.0f);
        glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 1.0f, -2.0f), glm::vec3(0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
	    int modelLocation = glGetUniformLocation(shaderProgram, "model");
	    glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(model));
	    int viewLocation = glGetUniformLocation(shaderProgram, "view");
	    glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(view));
	    int projLocation = glGetUniformLocation(shaderProgram, "projection");
	    glUniformMatrix4fv(projLocation, 1, GL_FALSE, glm::value_ptr(projection));

        // update shader uniform
        int vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor");
        glUniform3f(vertexColorLocation, 1.0f, 1.0f, 1.0f);


        ///
	    int lightPosLocation = glGetUniformLocation(shaderProgram, "lightPos");
	    glUniform3f(lightPosLocation, -5.0f, 5.0f, -5.0f);

        // render the triangle
	    glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();

        if (glGetError() != 0) {
        	printf("Error");
        }
    }

    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}

// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
    cur_width = width;
    cur_height = height;
}


void readFile(std::string const &filepath, std::string &content) {
    try {
        std::ifstream file;
        file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
        file.open(filepath);
        std::stringstream fStream;
        fStream << file.rdbuf();
        content = fStream.str();
        file.close();
    }
    catch (const std::exception &e) {
        throw std::runtime_error("Failed to load read file: " + filepath + " (" + e.what() + ")");
    }
}

void loadOBJ(std::string const &assetPath, std::vector<glm::vec3> &vertices, std::vector<GLuint> &indices) {
    // Load Mesh Data
    tinyobj::attrib_t attrib;
    std::vector<tinyobj::shape_t> shapes;
    std::vector<tinyobj::material_t> materials;

    std::string warn;
    std::string err;
    bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, assetPath.c_str());

    // Fatal Error
    if (!ret)
        throw std::runtime_error(std::string("Failed to load file: ") + assetPath + err);

    // Minor Error
    if (!err.empty()) {
        std::cout << err << std::endl;
    }

    // Convert Mesh Data
        tinyobj::mesh_t &mesh = shapes[0].mesh;
        for (size_t v = 0; v < mesh.indices.size(); v++) {
            // Note: This throws away any vertex reuse.
            // See http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-9-vbo-indexing/ for more information.
            indices.push_back((unsigned int) v);

            int vIndex = mesh.indices[v].vertex_index;
            int nIndex = mesh.indices[v].normal_index;

            glm::vec3 vector;
            // positions
            vector.x = attrib.vertices[3 * vIndex + 0];
            vector.y = attrib.vertices[3 * vIndex + 1];
            vector.z = attrib.vertices[3 * vIndex + 2];
            vertices.push_back(vector);

	        glm::vec3 normal;
	        // positions
	        normal.x = attrib.normals[3 * nIndex + 0];
	        normal.y = attrib.normals[3 * nIndex + 1];
	        normal.z = attrib.normals[3 * nIndex + 2];
	        vertices.push_back(normal);
        }

}




