// CMAMEApp.cpp
// The BApplication for MAME
// Casey Fleser
// October 24, 1997

#include <BeHeaders>

#include "CMAMEApp.h"
#include "CMainThread.h"
#include "CAbout.h"
#include "CROMSelector.h"
#include "Defines.h"

app_info			gAppInfo;

int main(int argc,char **argv)
{
	CMAMEApp *theApp = new CMAMEApp();
	
	theApp->Run();

	delete(theApp);

	return B_NO_ERROR;
}

CMAMEApp::CMAMEApp() :
	BApplication(kAppSig)
{
	GetAppInfo(&gAppInfo);		// get the app info here once to avoid nasty deadlocks later
	
	mMain = NULL;
}

bool
CMAMEApp::QuitRequested()
{
	if (mMain != NULL)
		delete mMain;
	
	return BApplication::QuitRequested();
}

void
CMAMEApp::ReadyToRun()
{
	if (mMain == NULL) {
		new CROMSelector();
//		PostMessage(B_QUIT_REQUESTED);
	}
}

void
CMAMEApp::MessageReceived(
	BMessage	*msg)
{
	switch (msg->what) {
		case eWhat_MAMEStatus:
			PostMessage(B_QUIT_REQUESTED);
			break;
			
		case eWhat_OpenROM: {
				type_code		theType;
				int32		argc;

				delete mMain;
					
				if (msg->GetInfo("argv", &theType, &argc) == B_NO_ERROR) {
					char		**argv;
					char		*msgStr;
					int32	index = 0;
					
					argc++;	// add the app name
					argv = (char **)::malloc(sizeof(char *) * argc);
					argv[0] = strdup("./BeMAME");
					while (msg->FindString("argv", index, &msgStr) == B_NO_ERROR) {
						index++;
						argv[index] = strdup(msgStr);
					}
					
					mMain = new CMainThread(argc, argv);
					mMain->Go();
					
					for (index=0; index<argc; index++)
						::free(argv[index]);
					::free(argv);
				}
			}
			break;
			
		case eWhat_SelectROM:
			new CROMSelector();
			break;
			
		case eWhat_SelROMCancel:
			if (mMain == NULL)
				PostMessage(B_QUIT_REQUESTED);
			break;
			
		default:
			BApplication::MessageReceived(msg);
			break;
	}
}

void	
CMAMEApp::ArgvReceived(
	int32	argc,
	char		**argv)
{
	mMain = new CMainThread(argc, argv);
	mMain->Go();
}

void
CMAMEApp::AboutRequested()
{
	CAbout::DoAbout();
}
