#include "texture.h"

namespace CBK
{
	Texture::Texture(const std::string& name, IDirect3DDevice9* device) : Object(device)
	{
		texture = 0;

		magFilter = D3DTEXF_LINEAR;
		minFilter = D3DTEXF_LINEAR;
		mipFilter = D3DTEXF_LINEAR;

		load(name);
	}

	const std::string& Texture::getName(void) const
	{
		return name;
	}

	Texture::~Texture(void)
	{
		if (texture != 0)
			d3d::Release<IDirect3DTexture9*>(texture);
	}

	Texture& Texture::load(const std::string& name)
	{
		if (device == 0) return *this;

		if (texture == 0)
			d3d::Release<IDirect3DTexture9*>(texture);

		if (name != "")
			D3DXCreateTextureFromFile(device, name.c_str(), &texture);
		else
			texture = 0;

		this->name = name;
		return *this;
	}

	Texture& Texture::setMipMapping(const DWORD& magFilter, const DWORD& minFilter, const DWORD& mipFilter)
	{
		this->magFilter = magFilter;
		this->minFilter = minFilter;
		this->mipFilter = mipFilter;

		return *this;
	}

	void Texture::apply(const DWORD& stage) const
	{
		if (device == 0) return;

		device->SetSamplerState(stage, D3DSAMP_MAGFILTER, magFilter);
		device->SetSamplerState(stage, D3DSAMP_MINFILTER, minFilter);
		device->SetSamplerState(stage, D3DSAMP_MIPFILTER, mipFilter);
		device->SetTexture(stage, texture);
	}

	void Texture::apply(void)
	{
		apply(0);
	}

	void Texture::clear(IDirect3DDevice9* device, const DWORD& stage)
	{
		device->SetTexture(stage, 0);
	}
}