#include "StdAfx.h"
#include "apl_gui.h"
#include "ProgressDlgThread.h"

bool CaplShowProgress::SetUserBreakText(LPCTSTR break_text)
{
	m_sBreakText = break_text;
	return true;
}

bool CaplShowProgress::Show(LPCTSTR title, LPCTSTR text)
{
	CProgressDlgThread *thread = (CProgressDlgThread*)AfxBeginThread(RUNTIME_CLASS(CProgressDlgThread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
	thread->m_Text = text;

	if(title) thread->m_sTitle = title;
	thread->ResumeThread();

	MSG msg; 
	while(!thread->IsInitialized())
	{		
		while (::PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE|  PM_NOYIELD)) 
			DispatchMessage(&msg);
	}

	m_Thread = (long)thread;
	return true;
}

bool CaplShowProgress::IncreaseValue(int val)
{
	if(m_Thread == 0) return false;
	if(val <= 0 || val > 100) return false;

	((CProgressDlgThread*)m_Thread)->IncreaseValue(val);
	return true;
}

bool CaplShowProgress::SetValue(int val)
{
	if(m_Thread == 0) return false;
	if(val <= 0 || val > 100) return false;

	((CProgressDlgThread*)m_Thread)->SetValue(val);
	return true;
}

bool CaplShowProgress::IsCanceledByUser()
{
	if(m_Thread == 0) return false;
	return ((CProgressDlgThread*)m_Thread)->m_bCanceled;
}

bool CaplShowProgress::Close()
{
	if(m_Thread == 0) return false;

	((CProgressDlgThread*)m_Thread)->m_End = 1;
	if(((CProgressDlgThread*)m_Thread)->m_bCanceled && m_sBreakText!=_T(""))
		AfxMessageBox(m_sBreakText, MB_ICONSTOP);

	CWnd *wnd=AfxGetMainWnd();
	if(wnd!=0) wnd->SetForegroundWindow( );	

	return true;
}

bool CaplShowProgress::SetText(LPCTSTR text)
{
	if(m_Thread == 0) return false;

	((CProgressDlgThread*)m_Thread)->SetText(text);
	return true;
}

bool CaplShowProgress::SetTitle(LPCTSTR title)
{
	if(m_Thread == 0) return false;

	((CProgressDlgThread*)m_Thread)->SetTitle(title);
	return true;
}

bool CaplShowProgress::DisableBreakButton()
{
	if(m_Thread == 0) return false;

	((CProgressDlgThread*)m_Thread)->DisableBreakButton();
	return true;
}