#include "texture.h"

Texture::Texture()
{
    fileName= QString();
    textureTarget = GL_TEXTURE_2D;
    textureObj = 0xFFFFFFFF;
}

void Texture::Load(GLenum textureTarget, QString fileName)
{
    this->textureTarget = textureTarget;
    this->fileName      = fileName;

    //load
    if(fileName.isEmpty()){
        qWarning() << "No Image to load";
        return;
    }

    qDebug() << "Loading Texture:" << fileName;

    QString suffix = QFileInfo(fileName).completeSuffix();

    if(suffix.endsWith("pcx")||suffix.endsWith("tga")){
        fileName.replace(QRegularExpression(suffix),QString("png"));
        suffix = QString("png");
    }

    if(!QFile::exists(fileName))
    {
         qDebug() << "File " << fileName << "don't exists";
        return;
    }

    QImage *texture =  new QImage(fileName, suffix.toStdString().c_str());

    if (texture == NULL|| texture->isNull()){
        qDebug() << "Could not load Texture:" << fileName << "Suffix:"<< suffix;
        qDebug() << QImageReader::supportedImageFormats();
        return;
    }

    QImage textureImg = QGLWidget::convertToGLFormat( *texture );

    glGenTextures( 1, &textureObj );
    glBindTexture( this->textureTarget, textureObj );

    glTexImage2D(this->textureTarget, 0, GL_RGBA, textureImg.width(), textureImg.height(), 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, textureImg.bits());

    // Filtering
    glTexParameteri( this->textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( this->textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR );


    glBindTexture( this->textureTarget, 0 );
    qDebug() << "Loaded texture"+fileName;
}

Texture::~Texture(){
    glDeleteTextures(1,&textureObj);
}

void Texture::bind(QOpenGLFunctions_4_3_Core *f, GLenum textureUnit){
    f->glActiveTexture(textureUnit);
    f->glBindTexture(textureTarget, textureObj);
}

