#include "global.h"
#include <commctrl.h>
#include "capp.h"
#include <new.h>
#include <stdlib.h>
#include "cmemory.h"
#include "cdatalog.h"

bool CApplication::Init()
{
	INITCOMMONCONTROLSEX icce;
	icce.dwSize = sizeof(icce);
	icce.dwICC = ICC_TREEVIEW_CLASSES|ICC_INTERNET_CLASSES;//ICC_WIN95_CLASSES ;//
	if (!InitCommonControlsEx(&icce))
		return false;

	//-----------------------------------------------------------------------------------------
	//inicializuj mechanizmy cinne v pripade chyby pri alokacii pamate
	_set_new_handler(memory_error);//aby operator new hlasil chybu
	_set_new_mode(1);//aby malloc hlasil chybu
	//-----------------------------------------------------------------------------------------

	options = _NEW(COptions());
	database = _NEW(CDatabase());
	mainWindow = _NEW(CMainWindow());

	return true;
}

void CApplication::Destroy()
{
	_DELETE(options);
	_DELETE(database);
	_DELETE(mainWindow);
}

int CApplication::memory_error(size_t )
{
#ifdef _DEBUG
	::MessageBox(NULL, "NEDOSTATOK PAMÄTE!","CApplication::memory_error", MB_ICONSTOP|MB_OK);
#else
	::MessageBox(NULL, "NEDOSTATOK PAMÄTE!","Aplikácia bude ukončená", MB_ICONSTOP|MB_OK);
#endif
	CApplication::abort();
	return -1;
}

void CApplication::abort()
{
	CDatabase *db = app.GetDatabase();
	if (db)
		db->Disconnect();
	::abort();
}

int CApplication::WaitLoop()
{
	MSG msg;
	while (GetMessage(&msg,0,0,0))
	{
		if (!TranslateAccelerator(mainWindow->GetHandle(),mainWindow->GetAccelerator(),&msg))
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return msg.wParam;
}

CDatabase* CApplication::GetDatabase()
{
	return database;
}

CApplication::CApplication()
{
	/*if (!(heap = ::HeapCreate(0, 0, 0)))
	{
		app.memory_error(0);
	}*/
}

CApplication::~CApplication()
{
	/*if (heap)
		::HeapDestroy(heap);*/
}