/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

#include <qapplication.h>
#include <qeventloop.h>

#include <dialogs.h>
#include <dbsdglobal.h>
#include <dbsdiconloader.h>
#include <unixprocess.h>
#include <frmterminaldisplay.h>
#include <translation.h>

#include <portscleanengine.h>

void frmCleanPorts::init() {
	Translation::translateWizard(this);

	DBSDIconLoader *iloader = DBSDGlobal::getIconLoader();
	pixWelcome->setPixmap(iloader->loadIcon("recycled", DBSDIconLoader::Size48x48));
	pixConfirm->setPixmap(iloader->loadIcon("button_ok", DBSDIconLoader::Size32x32));
	
	setHelpEnabled(pgWelcome, false);
	setHelpEnabled(pgOptions, false);
	setHelpEnabled(pgFinish, false);

	setFinishEnabled(pgFinish, true);
}


void frmCleanPorts::accept() {
	bool lib = chkLibClean->isChecked();
	int ports = grpSrc->selectedId(),
		 pkgs = grpPkg->selectedId();

	/* Processes that will be executed */
	QPtrList<QProcess>  processes;
	processes.setAutoDelete(true);

	/* Don't use portsclean if not necessary */
	if(ports == 1 || pkgs == 1 || lib) {
		int flags = 0;
		if(ports == 1)
			flags |= PortsCleanEngine::DistCleanNotInstalled;

		if(pkgs == 1)
			flags |= PortsCleanEngine::PkgCleanOutdated;

		if(lib)
			flags |= PortsCleanEngine::LibClean;

		QProcess *p = PortsCleanEngine::getProcess(flags);
		if(p != NULL)
			processes.prepend(p);
	}

	if(ports == 2)
		processes.prepend(PortsCleanEngine::getRemoveAllDistfilesProcess());

	if(pkgs == 2)
		processes.prepend(PortsCleanEngine::getRemoveAllPkgsProcess());

	if(!processes.isEmpty()) {
		QEventLoop  *appEvLoop = QApplication::eventLoop();
		frmTerminalDisplay dlg(this, NULL, true);

		TerminalDisplay *dsp = dlg.getTerminalDisplay();
		dsp->setClearOnSetProcess(false);
		dsp->clear();

		dlg.show();

		do {
			QProcess *p = processes.take(0);
			dsp->setProcess(p);

			if(!p->start()) {
				Dialogs::warnDlg(tr("Error: Process couldn't be started.\n"
										  "\n"
										  "Stopping."));
				QDialog::reject();
				return;
			}

			while(p->isRunning() && !dlg.wasCanceled())
				appEvLoop->processEvents(QEventLoop::WaitForMore);

			bool normalExit = p->normalExit();
			delete p;

			/* Don't asked when unnormal exit caused by user */
			if(dlg.wasCanceled() ||
				(!normalExit && !dlg.wasCanceled() &&
				 !Dialogs::question(tr("The current action failed:\n"
											  "'%1'\n"
											  "\n"
											  "Continue?").arg(p->arguments().join(" ")))))
			{
				QDialog::reject();
				return;
			}
		} while(!processes.isEmpty());

		Dialogs::infoDlg(tr("All operations finished successfully.\n"
								  "\n"
								  "Click 'Close'."));
		dlg.setFinished(true);
		dlg.exec();
	} else
		Dialogs::infoDlg(tr("No actions need to be done."));

	QDialog::accept();
}
