#include "GLTexture.h"
#include <cstdlib>
#include <ctime>

GLTexture::GLTexture()
    : handle(0) {
    makeTexture();
}

GLTexture::~GLTexture() {
   glDeleteTextures(1, &handle);
}

void GLTexture::makeTexture() {
    glGenTextures(1, &handle);
    glBindTexture(GL_TEXTURE_2D, handle);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}

int GLTexture::bind(int unit) {
    glActiveTexture(GL_TEXTURE0 + unit);
    glBindTexture(GL_TEXTURE_2D, handle);
    return unit;
}

void GLTexture::bind() {
    glBindTexture(GL_TEXTURE_2D, handle);
}

void GLTexture::setPixels(const unsigned char* data, int width, int height) {
    bind();
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);
}

void GLTexture::setPixelsRandom(int width, int height) {
    std::srand(std::time(nullptr));
    unsigned char* data = new unsigned char[width * height * 4];
    for (int i = 0; i < width * height * 4; i += 4) {
        data[i] = static_cast<unsigned char>(std::rand() % 256);
        data[i + 1] = static_cast<unsigned char>(std::rand() % 256);
        data[i + 2] = static_cast<unsigned char>(std::rand() % 256);
        data[i + 3] = 255;
    }
    setPixels(data, width, height);
    delete[] data;
}

void GLTexture::setPixelsEmpty() {
    unsigned char data[16] = {0};
    setPixels(data, 2, 2);
}

void GLTexture::setShape(int width, int height) {
    bind();
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
}

int GLTexture::getHandle() const {
    return static_cast<int>(handle);
}