// This is the main DLL file.

#include "stdafx.h"
#include "TextBoxConsole.h"
namespace TextConsole {
	
	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Windows::Forms;
	
	char* TextBoxConsole::Input(char* Buf, size_t nBufLen)
	{
		if(bInputMode) return NULL;
		
		this->Focus();
		bInputMode = true;
		strEnteredValue = "";
		// Ожидаем окончания ввода - значение bInputMode будет изменено после нажатия пользователем
		// на клавишу Enter
		while(bInputMode)
		{
		   System::Threading::Thread::Sleep(50); // Ожидаем 50 миллисекунд, чтобы дать поработать другим приложениям
		   Application::DoEvents();			 // Даём возможность системе обработать сообщения из очереди приложения
														 // Нажатия клавиатуры, сообщения мыши и др.
		}
		// Ввод был завершён пользователем, возвращаем введённые символы
		return ConvertStringToCharBuffer(strEnteredValue, Buf, nBufLen);
	}

	void TextBoxConsole::Write(const char*lpStrVal)
	{
		System::Text::Encoding^ encoding = System::Text::Encoding::UTF8;
		int len = strlen(lpStrVal);
		array<Byte>^ byteArray = gcnew array<Byte>(len+1);
		for(int i=0; i < len; i++)
		{
			byteArray[i] = *(lpStrVal+i);
		}
		byteArray[len] = '\0';
		System::String^ strText = encoding->GetString(byteArray);
		
		System::Windows::Forms::TextBox::AppendText(strText);
		System::Windows::Forms::TextBox::Refresh();
		Application::DoEvents(); 
	}

	void TextBoxConsole::NewLine()
	{
		System::String ^s = Environment::NewLine;
		System::Windows::Forms::TextBox::AppendText(s);
		System::Windows::Forms::TextBox::Refresh();
		Application::DoEvents();
	}


	void TextBoxConsole::OnKeyPress(System::Windows::Forms::KeyPressEventArgs^ e)
	{
		System::Windows::Forms::TextBox::OnKeyPress(e);
		if(! bInputMode) return;
		System::String^ strChar = System::Convert::ToString(e->KeyChar);
				 
		if(e->KeyChar == 13L)  // если пользователь ввёл 13L - код клавиши "Enter" - призгак окончания ввода
		{
			 bInputMode = false; // Устанавливаем прищнак окончания ввода
		}
		else 
		{
			strEnteredValue += strChar; // дописываем введённый символ к строке ввода
			this->AppendText(strChar); 
		}
		// Считаем, что редактирование разрешено и введённые символы уже отображаются
		// в поле ввода
	}

	char* TextBoxConsole::ConvertStringToCharBuffer(System::String^ strVal, char* Buf, size_t nBufLen)
	{
		size_t nConverted; // Число преобразованных символов
		
		array<wchar_t>^ wcharArray = strVal->ToCharArray();
		wchar_t* pWCBuffer = (wchar_t *)malloc( (strVal->Length +1) *sizeof(wchar_t));
		int k;
		
		for(k = 0;  k < strVal->Length; k++)
		{
			pWCBuffer[k] = wcharArray[k];
		}
		pWCBuffer[k] = 0L;

		// Преобразование
		wcstombs_s(	&nConverted, Buf, (size_t)nBufLen, 
					pWCBuffer, (size_t)k*2);
		free(pWCBuffer);
		return Buf;
	}
}
