#include "Mix/Private/Graphics/Utility/Common/Font.h"
#include "Mix/Memory/IBuffer.h"

namespace Mix{ namespace Graphics{ namespace Utility{ namespace Common{

const UInt32 Font::FNT_MAGICNUMBER = 0x4652504D; //マジック値
const UInt32 Font::FNT_VERSION     = 0x01020000; //バージョン

Boolean Font::CheckFormat( Mix::Memory::IBuffer* pBuffer )
{
	const Font::FILE_HEADER* pfh = static_cast<const Font::FILE_HEADER*>( pBuffer->GetConstPointer() );

	if( pfh->magicNumber != Font::FNT_MAGICNUMBER )
	{
		MIX_LOG_ERROR( L"%s", Mix::STR_ILLEGALFORMAT );
		return False;
	}

	if( pfh->version != Font::FNT_VERSION )
	{
		MIX_LOG_ERROR( L"%s : FileVersion[0x%08x] CurrentVersion[0x%08x]", Mix::STR_ERR_NOT_SUPPORT_VERSION, pfh->version, Font::FNT_VERSION );
		return False;
	}

	return True;
}

Font* Font::CreateInstance( Mix::Memory::IBuffer* pBuffer )
{
	return MIX_LIB_NEW_T( Mix::Memory::SECTION_GRAPHICS, Font, pBuffer );
}

Font::Font( Mix::Memory::IBuffer* pBuffer ) :
m_pBuffer( pBuffer ),
m_pFileHeader( NULL ),
m_pDataHeader( NULL ),
m_pCharaInfoArray( NULL )
{
	//各ポインタを設定
	m_pData = static_cast<const UInt8*>( m_pBuffer->GetConstPointer() );
	m_pFileHeader = reinterpret_cast<const Font::FILE_HEADER*>( m_pData );
	m_pDataHeader = reinterpret_cast<const Font::DATA_HEADER*>( m_pData + sizeof( Font::FILE_HEADER ) );
	m_pCharaInfoArray = reinterpret_cast<const Font::CHARA_INFO*>( m_pData + sizeof( Font::FILE_HEADER ) + sizeof( Font::DATA_HEADER ) );
}

Font::~Font( void )
{
	MIX_RELEASE( m_pBuffer );
}

Boolean Font::GetGlyph( wchar_t code, Mix::Graphics::Utility::IFont::GLYPH& glyph )
{
	if( ( m_pDataHeader->firstCode > code ) ||
		( m_pDataHeader->lastCode < code ) )
	{
		return False;
	}

	const Font::CHARA_INFO* pci = &( m_pCharaInfoArray[( code - m_pDataHeader->firstCode )] );

	glyph.pImg = ( m_pData + pci->imgAddr );
	glyph.cellWidth = pci->cellWidth;
	glyph.cellHeight = pci->cellHeight;
	glyph.x = pci->x;
	glyph.y = pci->y;
	glyph.width = pci->width;
	glyph.height = pci->height;

	return True;
}

UInt32 Font::GetEffects( void ) const
{
	return m_pDataHeader->effects;
}

UInt32 Font::GetHeight( void ) const
{
	return m_pDataHeader->height;
}

UInt32 Font::GetWeight( void ) const
{
	return m_pDataHeader->weight;
}

UInt32 Font::GetBorderSize( void ) const
{
	return m_pDataHeader->borderSize;
}

}}}}
