#include "GL/gl3w.h"
#include "GL/gl.h"
#include "TextureHelperOpenGL.hpp"

void TSE::OpenGL::TextureHelperOpenGL::Bind(const Texture *tex)
{
    glBindTexture(GL_TEXTURE_2D, tex->GetTextureId());
}

void TSE::OpenGL::TextureHelperOpenGL::UnBind(const Texture *tex)
{
    glBindTexture(GL_TEXTURE_2D, 0);
}

void TSE::OpenGL::TextureHelperOpenGL::Apply(Texture *tex)
{
    glBindTexture(GL_TEXTURE_2D, tex->GetTextureId());
        if(tex->Chanels() == 1)
        {
            if (tex->bpp() == 8)
                glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, tex->Width(), tex->Height(), 0, GL_RED, GL_UNSIGNED_BYTE, tex->GetImagePtr());
        }
        if(tex->Chanels() == 3)
        {
            if(tex->bpp() == 24)
                glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, tex->Width(), tex->Height(), 0, GL_BGR, GL_UNSIGNED_BYTE, tex->GetImagePtr());
        }
        else if(tex->Chanels() == 4)
        {
            if(tex->bpp() == 32)
                glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, tex->Width(), tex->Height(), 0, GL_BGRA, GL_UNSIGNED_BYTE, tex->GetImagePtr());
            if (tex->bpp() == 8) //need to decode it with bitwise operations in shader
                glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, tex->Width(), tex->Height(), 0, GL_RED, GL_UNSIGNED_BYTE, tex->GetImagePtr());
        }

        glGenerateMipmap(GL_TEXTURE_2D);

        glBindTexture(GL_TEXTURE_2D, 0);
}

void TSE::OpenGL::TextureHelperOpenGL::Regist(Texture *tex)
{
    uint TextureID;

    glGenTextures(1, &TextureID);
    glBindTexture(GL_TEXTURE_2D, TextureID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    
    tex->SetTextureId(TextureID);

    tex->Apply();
}

void TSE::OpenGL::TextureHelperOpenGL::PlatromDestroy(Texture *tex)
{
    uint id = tex->GetTextureId();
    glDeleteTextures(1, &id);
}
