#include "stdafx.h"
#include "TextPrinter.h"

void TextPrinter::SetRegion( int x, int y, int w, int h )
{
	m_x = x;
	m_y = y;
	m_w = w;
	m_h = h;
	m_cx = 0;
	m_cy = 0;
}

void TextPrinter::SetTextParams( int width, int height )
{
	m_textHeight = height;
	m_textWidth = width;
}

void TextPrinter::SetText( const wchar_t *pText )
{
	m_pText = pText;
	m_textLen = pText ? (int)wcslen( pText ) : 0;
	m_absIndex = 0;
	m_wordIndex = 0;
	m_wordEnd = 0;
	m_cx = 0;
	m_cy = 0;
}

bool TextPrinter::Update( ImageHandle image, IRender & render )
{
	if ( !m_pText )
		return false;

	if ( m_wordIndex >= m_wordEnd )
	{
		if ( m_absIndex >= m_textLen )
			return false;

		while( m_absIndex < m_textLen )
		{
			if ( m_pText[ m_absIndex ] == L' ' )
				break;
			++m_absIndex;
		}

		m_wordEnd = m_absIndex + 1;
		++m_absIndex;

		const int wordLen = m_wordEnd - m_wordIndex;
		if ( wordLen > 0 )
		{
			const int wordWidth = render.GetStringWidth( m_pText + (size_t)m_wordIndex, wordLen );
			if ( m_cx + wordWidth >= m_w )
			{
				m_cx = 0;
				m_cy += m_textHeight;
			}
		}
	}
	else
	{
		if ( iswprint( m_pText[ m_wordIndex ] ) )
		{
			render.DrawText( image, m_x + m_cx, m_y + m_cy, Color(255,255,255), m_textHeight, "%C", m_pText[ m_wordIndex ] );
			m_cx += m_textWidth;
		}
		else if ( iswspace( m_pText[ m_wordIndex ] ) && m_wordIndex > 0 && !iswspace( m_pText[ m_wordIndex - 1 ] ) )
			m_cx += m_textWidth;
		
		++m_wordIndex;
	}

	return true;
}
