// myplain.cpp

#include "myplain.h"

namespace mylib
{

CMyPlain::CMyPlain()
{
	m_nLines = 0;
	m_nWidth = 0;
	m_sz.cx = 0;
	m_sz.cy = 0;
}

CMyPlain::CMyPlain(const TCHAR* pszFileName)
{
	HANDLE hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, 0,
		OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, 0);

	if(hFile == INVALID_HANDLE_VALUE)
		return;

	m_nLines = 0;
	DWORD nRead = 0;
	unsigned char buf[2];
	while(1)
	{
		std::vector<TCHAR> linebuf;
		while(ReadFile(hFile, buf, 1, &nRead, 0))
		{
			if((nRead == 0) || (buf[0] == '\n'))
			{
				m_nLines++;
				m_linebuf.push_back(linebuf);
				break;
			}
			if(buf[0] > ' ')
				linebuf.push_back((TCHAR)buf[0]);
			else
				linebuf.push_back((TCHAR)' ');
		}
		if(nRead == 0)
		{
			CloseHandle(hFile);
			return;
		}
	}
	CloseHandle(hFile);
}

CMyPlain::~CMyPlain()
{
}

const SIZE&
CMyPlain::Size(HDC hdc)
{
	TEXTMETRIC tm;
	GetTextMetrics(hdc, &tm);
	int ystep = (int)(tm.tmHeight + tm.tmExternalLeading);
	m_sz.cx = (int)tm.tmAveCharWidth;
	m_sz.cy = ystep * m_nLines;
	std::vector<std::vector<TCHAR> >::iterator p = m_linebuf.begin();
	while(p != m_linebuf.end() )
	{
		if(p->size() > 0)
		{
			SIZE sz;
			std::vector<TCHAR>::iterator q = p->begin();
			if(GetTextExtentPoint32(hdc, &*q, p->size(), &sz))
			{
				if(sz.cx > m_sz.cx)
					m_sz.cx = sz.cx;
			}
		}
		p++;
	}
	return m_sz;
}

int
CMyPlain::Draw(HDC hdc, int x, int y, PAINTSTRUCT& ps)
{
	TEXTMETRIC tm;
	GetTextMetrics(hdc, &tm);
	int ystep = (int)(tm.tmHeight + tm.tmExternalLeading);
	std::vector<std::vector<TCHAR> >::iterator p = m_linebuf.begin();
	while(p != m_linebuf.end() )
	{
		if(p->size() > 0)
		{
			std::vector<TCHAR>::iterator q = p->begin();
			TextOut(hdc, x, y, &*q, p->size());
		}
		p++;
		y += ystep;
	}
	return 0;
}

}	// namespace mylib
