//
//  textview.h - text view implementation
//
//  $Id: textview.cpp 50 2014-02-07 02:18:02Z brian $ 
//
//  Copyright (c) 1999-2014 by Precision Micro Control Corp. All rights reserved.
//
#include "stdafx.h"

IMPLEMENT_DYNCREATE(CTextView, CView)

BEGIN_MESSAGE_MAP(CTextView, CView)
END_MESSAGE_MAP()

CTextView::CTextView()
	: m_blank_text(" "), m_char_height(0), m_first_string(0)
{
	Blank();						// Blank will clear display CStrings
}

void CTextView::OnDraw(CDC* pDC)
{
	if (m_char_height == 0)
	{
		TEXTMETRIC tm;
		if (pDC->GetTextMetrics(&tm))
			m_char_height = tm.tmHeight;
		else
			m_char_height = DEFAULT_CHAR_HEIGHT;
	}
	
	RECT rect;
	GetClientRect(&rect);
	int viewable_lines = rect.bottom / m_char_height;
	if (viewable_lines > MAX_LINES)
		viewable_lines = MAX_LINES;
	
	for (int i = 0; i < viewable_lines; i++)
	{
		int string_index = (i + m_first_string) % MAX_LINES;
		CString* string = &m_disp_string[string_index];
		if (string->IsEmpty())			// Check for empty string, use blank string to clear line
			string = &m_blank_text;
		pDC->TextOut(3, (viewable_lines - i - 1) * m_char_height, *string);
	}
}

void CTextView::OutputText(LPCSTR string)
{
	CString Text(string);
	
	int text_len = Text.GetLength();
	while (text_len > 0)
	{
		int line_term_index = Text.Find('\r');
		
		if (line_term_index < 0)
		{				
			// No carriage return in text, append entire line to display string
			m_disp_string[m_first_string] += Text;
			Text.Empty();
		}
		else
		{
			// Carriage return somewhere in the middle, append preceding text to display string
			if (line_term_index > 0)
				m_disp_string[m_first_string] += Text.Left(line_term_index);
			
			// Remove text up to the carriage return from string
			Text = Text.Right(text_len - (line_term_index + 1));

			// Since a carriage return has been encountered, adjust the first string 
			// pointer and clear that string in preparation for succeding text.
			m_first_string--;
			if (m_first_string < 0)
				m_first_string = MAX_LINES - 1;

			m_disp_string[m_first_string].Empty();
		}
		text_len = Text.GetLength();
	}
	
	Invalidate(TRUE);		// Invalidate display window
}

void CTextView::Erase()
{
	Blank();				// Blank will clear text CStrings
	Invalidate(TRUE);		// Invalidate display window
}


void CTextView::Blank()
{
	for (int i = 0; i < MAX_LINES; i++)
		m_disp_string[i].Empty();
}
