#include "mainwindow.h"

KMameleon::KMameleon()
{
//inits...
	helpMenu = new KHelpMenu(this, KGlobal::instance()->aboutData(), true);
	config = kapp->config();
	mnuPopup = new KPopupMenu(this);
	toolPopup = new KPopupMenu(this);
	loadPopups();

	dbgWindow = new DevDebug( 0, "dlg_debug", WStyle_Customize | WStyle_Tool );
	newConfig = new XMameCfg();
	options = "";

//button pixmaps
	setFixedSize(450, 55);
	setCaption(i18n("KMameleon %1").arg(DEF_VERSION));
	btnCfg->setPixmap(QPixmap(locate("data","kmameleon/pics/conf.png")) );
	btnPlay->setPixmap(QPixmap(locate("data","kmameleon/pics/play.png")) );
	btnQuit->setPixmap(QPixmap(locate("data","kmameleon/pics/off.png")) );
	btnHelp->setPixmap(QPixmap(locate("data","kmameleon/pics/help.png")) );
	btnStop->setPixmap(QPixmap(locate("data","kmameleon/pics/stop.png")) );
	btnReload->setPixmap(QPixmap(locate("data","kmameleon/pics/reload.png")) );
	btnTools->setPixmap(QPixmap(locate("data","kmameleon/pics/tools.png")) );

//connections
	connect (btnQuit, SIGNAL(clicked()), this, SLOT(close()) );
	connect (btnPlay, SIGNAL(clicked()), this, SLOT(runPlay()) );
	connect (btnStop, SIGNAL(clicked()), this, SLOT(goStop()) );
	connect (btnCfg, SIGNAL(clicked()), this, SLOT(runConf()) );
	connect (newConfig, SIGNAL(listenConfOk()), this, SLOT(reloadList()) );
	connect (btnHelp, SIGNAL(clicked()), this, SLOT(popHelp()) );
	connect (btnTools, SIGNAL(clicked()), this, SLOT(popTools()) );
	connect (btnReload, SIGNAL(clicked()), this, SLOT(reloadList()) );
	connect(&proc, SIGNAL( receivedStderr(KProcess *, char *, int)), this, SLOT( getErrOutput( KProcess *, char *, int)) );
	connect(&proc, SIGNAL( receivedStdout(KProcess *, char *, int)), this, SLOT( getOutput( KProcess *, char *, int)) );
	connect(&proc, SIGNAL( processExited (KProcess *)), this, SLOT( getStoppedStatus(KProcess *)) );

//tooltips
	QToolTip::add(btnQuit, i18n("Exit KMameleon"));
	QToolTip::add(btnPlay, i18n("Let\'s play games!"));
	QToolTip::add(btnCfg, i18n("Configure KMameleon"));
	QToolTip::add(btnStop, i18n("Stop currently running xmame"));
	QToolTip::add(btnHelp, i18n("Help"));
	QToolTip::add(btnReload, i18n("Reload Gamelist"));
	QToolTip::add(btnTools, i18n("KMameleon tools"));

//loading directory list, if the ROM path is defined...
	reloadList();

//locking the "stop" button
	btnStop->setEnabled(false);

//loading the tools...
	romChecker = new ToolRomCheckerPlugin();
	pathFinder = new ToolPathFinderPlugin();
	romLister = new ToolRomListerPlugin();

}

KMameleon::~KMameleon()
{
}

QString KMameleon::modes(int mode)
{
	bool conf_isFullscreen;
	if (mode == 0)
	{
		conf_xmameBinPath=config->readEntry("xmame_sdl","");
		if(! conf_xmameBinPath.isEmpty())
		{
			kdDebug() << "SDL" << endl;
			config->setGroup("screen");
			conf_isFullscreen=config->readBoolEntry("sdl_fullscreen",false);
			if (conf_isFullscreen == true)
				fsOptions += "  -fullscreen";
		}
	}
	else if(mode == 1)
	{
		conf_xmameBinPath=config->readEntry("xmame_x11","");
		if(! conf_xmameBinPath.isEmpty())
		{
			kdDebug() << "X11" << endl;
			config->setGroup("screen");
			conf_isFullscreen=config->readBoolEntry("x11_fullscreen",false);
			if (conf_isFullscreen == true)
				fsOptions += "  -x11 1";
		}
	}
	else if(mode == 2)
	{
		conf_xmameBinPath=config->readEntry("xmame_gl","");
		if(! conf_xmameBinPath.isEmpty())
		{
			kdDebug() << "XGL" << endl;
			config->setGroup("screen");
			conf_isFullscreen=config->readBoolEntry("gl_fullscreen",false);
			if (conf_isFullscreen == true)
				fsOptions += "  -fullscreen";
		}
	}
	else if(mode == 3)
	{
		conf_xmameBinPath=config->readEntry("xmame_svga","");
		if(! conf_xmameBinPath.isEmpty())
		{
			kdDebug() << "SVGALIB" << endl;
			config->setGroup("screen");
			conf_isFullscreen=config->readBoolEntry("fullscreen_svga",false);
			if (conf_isFullscreen == true)
				fsOptions += "  -fullscreen";
		}
	}
	return conf_xmameBinPath;
}

void KMameleon::runPlay()
{
	int xmame_type;

	dbgWindow->dbgOut->setText("");

	config->setGroup("general");
	xmame_type=config->readNumEntry("xmame_type",0);


	switch (xmame_type)
	{
		case 0:
			if (! modes(0).isEmpty())
				break;
			if (! modes(1).isEmpty())
				break;
			if (! modes(2).isEmpty())
				break;
			if (! modes(3).isEmpty())
				break;
		break;

		case 1:
			config->setGroup("general");
			conf_xmameBinPath=config->readEntry("xmame_sdl","");
		break;

		case 2:
			config->setGroup("general");
			conf_xmameBinPath=config->readEntry("xmame_x11","");
		break;

		case 3:
			config->setGroup("general");
			conf_xmameBinPath=config->readEntry("xmame_gl","");
		break;
	}

	config->setGroup("general");
	conf_selectedGame=lstGames->currentText();

	proc.clearArguments();
	#if KDE_VERSION >= 306
		proc.setUseShell(true);
	#endif

	if (! conf_selectedGame.isEmpty())
	{
		if (! conf_xmameBinPath.isEmpty())
		{
			config->setGroup("xmame_options");
			options=config->readEntry("current_options", "");
			kdDebug() << options << fsOptions << endl;

			proc << conf_xmameBinPath << options.local8Bit() << fsOptions << conf_selectedGame;

			if (proc.start(KProcess::NotifyOnExit, KProcess::AllOutput) == false)
				KMessageBox::error( 0, i18n("Couldn't load a program") );

			if (proc.isRunning())
				btnStop->setEnabled(true);
		}
		else
			KMessageBox::error( 0, i18n("XMame binary path seems to be missing") );

		kdDebug() << xmame_type << endl;
		kdDebug() << conf_xmameBinPath << endl;
		kdDebug() << options << endl;
		options="";
	}
	else
		KMessageBox::error( 0, i18n("No roms are selected to play") );
}

void KMameleon::runConf()
{
	newConfig->show();
}

void KMameleon::reloadList()
{
//for now; we'll load path from the config fle..
	config->setGroup("general");
	QString mameRomPath = config->readEntry("xmame_rom","");

	if (! mameRomPath.isEmpty())
	{
		QStringList gamesList;
		lstGames->clear();
		gamesList.clear();

		QDir d(mameRomPath);
		d.setFilter( QDir::Dirs);

		for ( unsigned int i=0; i<d.count(); i++ )
		{
			if ((d[i] != ".") && (d[i] != ".."))
			{
				gamesList += d[i];
				kdDebug() << "Adding game name [directory]: " << d[i] << endl;
			}
		}

		d.setFilter( QDir::Files);
		QStringList zipGamesList = d.entryList("*.zip");
		for (unsigned int i=0; i<zipGamesList.count(); i++)
		{
				QFileInfo fi(zipGamesList[i]);
				if (gamesList.findIndex(fi.baseName()) == -1)
				{
					kdDebug() << "Adding game name [zip]: " << fi.baseName() << endl;
					gamesList += fi.baseName();
				}
				else
				{
					kdDebug() << "Ignoring game name [zip]: " << fi.baseName() << endl;
				}
		}

		QStringList bZipGamesList = d.entryList("*.tar.bz2");
		for (unsigned int i=0; i<bZipGamesList.count(); i++)
		{
			QFileInfo fi(bZipGamesList[i]);
				if (gamesList.findIndex(fi.baseName()) == -1)
				{
					kdDebug() << "Adding game name [bZip2]: " << fi.baseName() << endl;
					gamesList += fi.baseName();
				}
				else
					kdDebug() << "Ignoring game name [zip]: " << fi.baseName() << endl;
		}

		kdDebug() << "Sorting list..." << endl;
		gamesList.sort();
		lstGames->insertStringList(gamesList);
		kdDebug() << gamesList.count() << endl;
	}

//we'll check, weither it is up to show the debug window, too...
	config->setGroup("general");
	if (config->readBoolEntry("showOutput",false) == true)
		dbgWindow->show();
	else
		dbgWindow->hide();
}

void KMameleon::loadPopups()
{
//help menu...
	mnuPopup = helpMenu->menu();

//Tools & gadgets...
	toolPopup->setTitle(i18n("Tools"));
	toolPopup->insertItem(QPixmap(locate("data","kmameleon/tools/img_romcheck.png")), i18n("Rom checker"), this, SLOT(loadRomChecker()));
	toolPopup->insertItem(QPixmap(locate("data","kmameleon/tools/img_pathfinder.png")), i18n("Path finder"), this, SLOT(loadPathFinder()));
	toolPopup->insertItem(QPixmap(locate("data","kmameleon/tools/img_romlister.png")), i18n("Rom lister"), this, SLOT(loadRomLister()));
}

void KMameleon::popHelp()
{
	mnuPopup->exec(QCursor::pos());
}

void KMameleon::popTools()
{
	toolPopup->exec(QCursor::pos());
}

void KMameleon::getOutput(KProcess *, char *text, int len)
{
	temp.fill(' ',len+1);
	temp.replace(0,len,text);
	temp[len]='\0';

//colorful output...
	QString dta="\0";
	dta = "<font color=\"red\">" + temp + "</font><br>";
	kdDebug() << dta << endl;

	config->setGroup("general");
	if (config->readBoolEntry("color_debug",false)==true)
		dbgWindow->dbgOut->append(dta.local8Bit());
	else
		dbgWindow->dbgOut->append(temp.local8Bit());

	kdDebug() << dbgWindow->dbgOut->text() << endl;
}

void KMameleon::getErrOutput(KProcess *, char *text, int len)
{
	temp.fill(' ',len+1);
	temp.replace(0,len,text);
	temp[len]='\0';
//rather write output in the debug window as the kdDebug()
	dbgWindow->dbgOut->append(temp.local8Bit());
}

void KMameleon::goStop()
{
	if (proc.kill() != true)
		KMessageBox::error(this,i18n("Can't tell current XMame session to stop!"));
}

void KMameleon::getStoppedStatus(KProcess *)
{
	btnStop->setEnabled(false);
}

//from here on... The tools are loaded [NO exceptions!!!]
void KMameleon::loadRomChecker()
{
//	pathFinder->hide();
	romChecker->show();
}

void KMameleon::loadPathFinder()
{
//	romChecker->hide();
	pathFinder->show();
}

void KMameleon::loadRomLister()
{
	romLister->show();
}

void KMameleon::closeEvent(QCloseEvent)
{
	config->setGroup("general");
	if(config->readBoolEntry("detachProcess", false) == false)
		proc.kill();

	kapp->exit();
}
#include "mainwindow.moc"
