/*
 *  <Short Description>
 *  Copyright (C) 2023  Brett Terpstra
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_PERLIN_IMPLEMENTATION

#include <blt/gfx/stb/stb_image_write.h>

#if defined(__GNUC__) || defined(__GNUG__)
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Warray-bounds"
    
    #include <blt/gfx/stb/stb_image_resize2.h>
    
    #pragma GCC diagnostic pop
#else
    #include <blt/gfx/stb/stb_image_resize2.h>
#endif

#include <blt/gfx/stb/stb_image.h>
#include <blt/gfx/stb/stb_perlin.h>
#include <blt/gfx/texture.h>

blt::gfx::texture_file::texture_file(const std::string& path, const std::string& name): m_name(name.empty() ? path : name), m_path(path)
{
    stbi_set_flip_vertically_on_load(true);
    m_texture.m_data = stbi_load(
            m_path.c_str(),
            reinterpret_cast<int*>(&m_texture.m_width), reinterpret_cast<int*>(&m_texture.m_height),
            reinterpret_cast<int*>(&m_texture.m_channels),
            0
    );
}

blt::gfx::texture_file& blt::gfx::texture_file::resize(int target_width, int target_height)
{
    if (target_width == m_texture.width() && target_height == m_texture.height())
        return *this;
    // since we will be replacing the loaded data pointer, is it wise to use the allocator
    // that matches with what stb image uses, which is malloc, since we unload with stbi_image_free -> (free)
    auto* output_Data = (unsigned char*) malloc(
            target_width * target_height * m_texture.channels()
    );
    
    // resize the texture
    if (stbir_resize_uint8_linear(
            // input
            m_texture.m_data, m_texture.width(), m_texture.height(), 0,
            // output
            output_Data, target_width, target_height, 0,
            // channels
            static_cast<stbir_pixel_layout>(m_texture.channels())
    ))
    {
        BLT_WARN("Error resizing block texture image!");
    }
    
    // free up the old data
    stbi_image_free(m_texture.m_data);
    m_texture.m_data = output_Data;
    m_texture.m_width = target_width;
    m_texture.m_height = target_height;
    
    return *this;
}

void blt::gfx::texture_gl::setDefaults() const
{
    glTexParameteri(textureBindType, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(textureBindType, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // nearest preserves the pixely look
    glTexParameteri(textureBindType, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
    glTexParameteri(textureBindType, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_LINEAR);
#ifdef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
    // Anisotropy helps preserve textures at oblique angles
                float a = 0;
                glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &a);
                glTexParameterf(textureBindType, GL_TEXTURE_MAX_ANISOTROPY_EXT, a);
#endif
}

void blt::gfx::texture_gl2D::upload(void* data, GLint dataColorMode, int level, int x_offset, int y_offset, int sub_width, int sub_height) const
{
    if (sub_width < 0)
        sub_width = m_width;
    if (sub_height < 0)
        sub_height = m_height;
    bind();
    glTexSubImage2D(textureBindType, level, x_offset, y_offset, sub_width, sub_height, dataColorMode, GL_UNSIGNED_BYTE, data);
    unbind();
}

void blt::gfx::texture_gl2D::upload(const blt::gfx::texture_file& tex_file) const
{
    upload(tex_file.texture().data(), tex_file.channels() == 4 ? GL_RGBA : GL_RGB, 0, 0, 0, tex_file.width(), tex_file.height());
}

void blt::gfx::texture_gl2D::resize(int width, int height)
{
    m_width = width;
    m_height = height;
    bind();
    glTexStorage2D(textureBindType, 0, textureColorMode, m_width, m_height);
    unbind();
}

blt::gfx::texture_gl2D::texture_gl2D(int width, int height, GLint colorMode): texture_gl(width, height, GL_TEXTURE_2D, colorMode)
{
    bind();
    setDefaults();
    // TODO:
    const int MIPMAP_LEVELS = 4;
    glTexStorage2D(textureBindType, MIPMAP_LEVELS, colorMode, width, height);
}

blt::gfx::texture_gl2D::texture_gl2D(const blt::gfx::texture_data& data): texture_gl(data.width(), data.height(), GL_TEXTURE_2D, GL_RGBA8)
{
    bind();
    setDefaults();
    glTexStorage2D(textureBindType, 4, GL_RGBA8, data.width(), data.height());
    upload((void*) data.data(), data.channels() == 4 ? GL_RGBA : GL_RGB, 0, 0, 0, data.width(), data.height());
    bind();
    //glTexImage2D(textureBindType, 0, GL_RGBA, data.width(), data.height(), 0, data.channels() == 4 ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, (void*)data.data());
    generateMipmaps();
    unbind();
}

void blt::gfx::gl_texture2D_array::upload(void* data, int index, GLint dataColorMode, int level, int x_offset, int y_offset, int sub_width,
                                          int sub_height) const
{
    if (sub_width < 0)
        sub_width = m_width;
    if (sub_height < 0)
        sub_height = m_height;
    bind();
    glTexSubImage3D(
            textureBindType, level, x_offset, y_offset, index, sub_width, sub_height, 1,
            dataColorMode, GL_UNSIGNED_BYTE, data
    );
    generateMipmaps();
    unbind();
}

blt::gfx::gl_texture2D_array::gl_texture2D_array(int width, int height, int layers, GLint colorMode): texture_gl(width, height, layers, colorMode)
{
    bind();
    setDefaults();
    // 6+ mipmaps is about where I stop noticing any difference (size is 4x4 pixels, so that makes sense)
    glTexStorage3D(textureBindType, 6, colorMode, width, height, layers);
    BLT_DEBUG("Creating 2D Texture Array with ID: %d", textureID);
}
