#include "Texture.h"
#include <iostream>

#define STB_IMAGE_IMPLEMENTATION
#include "Util/stb_image.h"

bool Texture::is_valid() const {
    return valid;
}

uint Texture::load_texture(const std::string &path, Settings settings) {
    uint gl_id;

    glGenTextures(1, &gl_id);
    glBindTexture(GL_TEXTURE_2D, gl_id);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    if (settings.mipmaps) {
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    } else {
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    }
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    int width, height, nrChannels;
    unsigned char *data = stbi_load(path.c_str(), &width, &height, &nrChannels, 0);

    if (data) {
        // Check number of channels
        unsigned int glChannels = GL_RED;
        if (nrChannels == 3)
            glChannels = GL_RGB;
        else if (nrChannels == 4)
            glChannels = GL_RGBA;

        glTexImage2D(GL_TEXTURE_2D, 0, glChannels, width, height, 0, glChannels, GL_UNSIGNED_BYTE,
                     data);

        if (settings.mipmaps) {
            glGenerateMipmap(GL_TEXTURE_2D);
        }

        valid = true;
    }

    stbi_image_free(data);

    return gl_id;
}

void Texture::bind_to(int unit) {
    glActiveTexture(GL_TEXTURE0 + unit);
    glBindTexture(GL_TEXTURE_2D, id);
}