#pragma once
#include "image.h"

class Texture2D
{
    GLuint m_tex = 0;
    int m_width = 0;
    int m_height = 0;
    GLint m_format = 0;
    GLint m_iformat = 0;
public:
    bool auto_destroy = false;
    bool has_mips = false;
    bool create(int width, int height, GLint internal_format = GL_RGBA8, GLint format = GL_RGBA, const uint8_t* data = nullptr);
    bool create(const Image& img);
    void assign(GLuint tex, int w = -1, int h = -1, GLuint internal_format = GL_RGBA8, GLuint format = GL_RGBA);
    bool load(std::string filename);
    bool load_file(std::string filename);
    void destroy() { if (m_tex) /*LOG("TEX destroy %d", m_tex);*/ glDeleteTextures(1, &m_tex); m_tex = 0; }
    void bind() const { glBindTexture(GL_TEXTURE_2D, m_tex); }
    void unbind() const { glBindTexture(GL_TEXTURE_2D, 0); }
    void update(const uint8_t* data);
    bool ready() const { return m_tex != 0; }
    void create_mipmaps();
    glm::vec2 size() const;
    ~Texture2D();
};

class Sampler
{
    GLuint id = 0;
    mutable GLint current_unit = 0;
public:
    bool create(GLint filter = GL_LINEAR, GLint wrap = GL_CLAMP_TO_EDGE);
    void set(GLint filter = GL_LINEAR, GLint wrap = GL_CLAMP_TO_EDGE);
    void set_filter(GLint filter_min, GLint filter_mag);
    void set_border(glm::vec4 rgba);
    void bind(int unit) const;
    void unbind();
    bool ready() const { return id != 0; }
};

class TextureManager
{
public:
    static std::map<uint16_t, Texture2D> m_textures;
    static bool load(const char* path, bool generate_mipmpas = false);
    static void assign(uint16_t id, GLuint tex, int w = -1, int h = -1, GLuint internal_format = GL_RGBA8, GLuint format = GL_RGBA);
    static Texture2D& get(uint16_t id);
    static void invalidate();
};
