#include "mof/private/TextureImpl.hpp"
#include "mof/ConsoleIO.hpp"
#include "mof/private/FileTextureBuilder.hpp"
#include "mof/private/PixelMapTextureBuilder.hpp"

mof::Texture::Texture( const tstring& filename)
: m_pImpl(new Impl())
{
	m_pImpl->pTexture = mof::FileTextureBuilder( filename).create();
	D3DSURFACE_DESC desc;
	m_pImpl->pTexture->GetLevelDesc(0 , &desc);
	m_pImpl->width = desc.Width;
	m_pImpl->height = desc.Height;
}

mof::Texture::Texture( const std::shared_ptr<mof::PixelMap>& pPixelMap)
: m_pImpl(new Impl())
{
	m_pImpl->pTexture = mof::PixelMapTextureBuilder(pPixelMap).create();
	D3DSURFACE_DESC desc;
	m_pImpl->pTexture->GetLevelDesc(0 , &desc);
	m_pImpl->width = desc.Width;
	m_pImpl->height = desc.Height;
}

mof::Texture::~Texture(){}

std::shared_ptr<mof::PixelMap> mof::Texture::getPixelMap(){
	typedef mof::PixelMap::size_type size_type;
	boost::array<size_type , 2> sizes = {{getWidth() , getHeight()}};
	
	std::shared_ptr<mof::PixelMap> pMap(new mof::PixelMap(sizes));
	D3DLOCKED_RECT rect;
	m_pImpl->pTexture->LockRect(0 , &rect , NULL , 0);
	for(int y = 0 ; y < getHeight() ; y++){	
		for(int x = 0 ; x < getWidth() ; x++){
			BYTE* pPixel = (BYTE*)rect.pBits + x * 4 + y * rect.Pitch;
			(*pMap)[x][y] = mof::createColor(*(pPixel + 3) , *(pPixel+2) , *(pPixel+1) , *(pPixel));
		}
	}
	m_pImpl->pTexture->UnlockRect(0);
	return pMap;
}

int mof::Texture::getWidth(){
	return m_pImpl->width;
}

int mof::Texture::getHeight(){
	return m_pImpl->height;
}


