#include "pw/visual/texture.hpp"

#include <glad/glad.h>

namespace pw {


struct texture::impl {

	texture &_host;

	GLuint _texture_id;
	GLuint _texture_sampler;

	impl(texture& host)
		: _host(host)
	{
	}

	GLuint gl_shape() {
		switch (_host.shape()) {
		case data_layout::shape_1d:
			return GL_TEXTURE_1D;
		case data_layout::shape_2d:
			return GL_TEXTURE_2D;
		case data_layout::shape_3d:
			return GL_TEXTURE_3D;
		}
	}

	void create()
	{
		glGenTextures(1, &_texture_id);
		glBindTexture(gl_shape(), _texture_id);

//		glTexImage1D(gl_shape(), 0, GL_R8, cosAngleResolution, 0,
//			GL_RED, GL_UNSIGNED_BYTE, &textureData[0]);
//		glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_BASE_LEVEL, 0);
//		glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
//		glBindTexture(GL_TEXTURE_1D, 0);

		glGenSamplers(1, &_texture_sampler);
		glSamplerParameteri(_texture_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glSamplerParameteri(_texture_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);


		glSamplerParameteri(_texture_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);

//		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);

		glBindTexture(gl_shape(),0);
	}

	void destroy()
	{

	}

	void generate_mipmaps()
	{
		glGenerateMipmap(gl_shape());
	}
};



//
//
//

texture::texture()
{
	_impl = make_unique<impl>(*this);
}

texture::texture(shared_ptr<image> i, texture::data_layout s, texture::data_type t)
{
	texture();
	set_image(i);
	set_shape(s);
	set_type(t);
}

void texture::set_image(shared_ptr<image> i)
{
	_image = i;
}

void texture::set_type(texture::data_type t)
{
	_type = t;
}

void texture::set_shape(data_layout s)
{
	_shape = s;
}

void texture::set_wrap(wrap_mode w)
{
	_wrap = w;
}

void texture::generate_mipmaps()
{
	_impl->generate_mipmaps();
}

unsigned int texture::native_handle() const
{
	return _impl->_texture_id;
}

unsigned int texture::native_sampler_handle() const
{
	return _impl->_texture_sampler;
}


}
