#include "mof/private/PixelMapTextureBuilder.hpp"
#include "mof/private/GraphicsDeviceImpl.hpp"
#include <list>
#include <memory>
#include "mof/ConsoleIO.hpp"
#include "mof/Font.hpp"


mof::PixelMapTextureBuilder::PixelMapTextureBuilder( const std::shared_ptr<mof::PixelMap>& pixelMap)
: m_pPixelMap(pixelMap)
{
}

mof::PixelMapTextureBuilder::~PixelMapTextureBuilder(void)
{
	
}


LPDIRECT3DTEXTURE9 mof::PixelMapTextureBuilder::create(){
	HRESULT hr;
	LPDIRECT3DDEVICE9 pDevice = mof::GraphicsDevice::getRawDevice();

	unsigned int tWidth = 2;
	while(tWidth < m_pPixelMap->shape()[0])tWidth *= 2;
	unsigned int tHeight = 2;
	while(tHeight < m_pPixelMap->shape()[1])tHeight *= 2;
	
  
	// テクスチャ作成
	LPDIRECT3DTEXTURE9 texture;
	if
    (
        FAILED
        (
            hr = D3DXCreateTexture
                (
                    pDevice , tWidth , tHeight ,
                    1 , D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, 
                    D3DPOOL_DEFAULT, &texture
                )
        )
    )
    {
		throw std::runtime_error("Failed --- D3DXCreateTexture");
	}

   

	// テクスチャにフォントビットマップ書き込み
	D3DLOCKED_RECT LockedRect;
	if(FAILED(hr = texture->LockRect(0, &LockedRect, NULL, D3DLOCK_DISCARD))){
		throw std::runtime_error("Failed --- LockRect");
	}

	// フォント情報の書き込み
	
	FillMemory(LockedRect.pBits , LockedRect.Pitch * tHeight , 0);
	for(unsigned int y = 0 ; y < m_pPixelMap->shape()[1] ; y++){
		for(unsigned int x = 0 ; x < m_pPixelMap->shape()[0] ; x++){
			memcpy((BYTE*)LockedRect.pBits + LockedRect.Pitch * y + 4 * x , &((*m_pPixelMap)[x][y]) , sizeof(DWORD));
		}
	}

	
	texture->UnlockRect(0);
	return texture;


}

