/***************************************************************************
                          NewCdDialog.cpp  -  description
                             -------------------
    begin                : Sun May 13 2001
    copyright            : (C) 2001 by Alexy Podolsky
    email                : alexpod@users.sourceforge.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
//#include <iostream.h>

#include <qstring.h>
#include <qcombobox.h>
#include <qtooltip.h>
#include <qslider.h>
#include <qspinbox.h>
#include <qdir.h>
#include <qlabel.h>
#include <qcheckbox.h>
#include <qstringlist.h>
#include <qradiobutton.h>
#include <qlistview.h>
#include <qevent.h>
#include <qdatetime.h>
#include <qlcdnumber.h>
#include <qregexp.h>

#include <kiconloader.h>
#include <kprocess.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kconfig.h>
#include <kurl.h>
#include <kdebug.h>

#include "CdboDialogBase.h"
#include "CdboDialogActionFactory.h"

#include "NewCdDialogBase.h"
#include "NewCdDialog.h"
#include "NewCdDialog.moc"
#include "EraseDialog.h"
#include "PreviewDialog.h"

#include "dialogParts/DriveInfoPnl.h"
#include "dialogParts/SpeedPnl.h"
#include "dialogParts/DialogCntPnl.h"

#define BURN 0
#define CREATE 1
#define CREATE_ONLY 2

NewCdDialog::NewCdDialog(QWidget *parent, const char *name, QString image) :
	NewCdDialogBase(parent,name,true),
	CdboDialogBase(CdboDialogBase::NewCdDialogType){
	//////////////
	
	createImageOnly = false;
	createImage = false;
	if(!image.isEmpty())
		imageLbl->setText(image);
	fileList = 0;
	isoFileMappings = 0;
	init();
}
//---------------------------------------------------------------------------------------------
NewCdDialog::NewCdDialog(QStringList *flist, QWidget *parent, const char *name, bool createImageOnly ) :
	NewCdDialogBase(parent,name,true),
	CdboDialogBase(CdboDialogBase::NewCdDialogType){
	//////////////
	this->createImageOnly = createImageOnly;
	fileList = flist;
	isoFileMappings = 0;

	createImage = true;
	
	init();
}
//---------------------------------------------------------------------------------------------
NewCdDialog::NewCdDialog(QString *mappings, QWidget *parent, const char *name, bool createImageOnly ) :
	NewCdDialogBase(parent,name,true),
	CdboDialogBase(CdboDialogBase::NewCdDialogType){
	//////////////
	this->createImageOnly = createImageOnly;
	fileList = 0;
	isoFileMappings = mappings;
		
	createImage = true;
	
	init();
}
//---------------------------------------------------------------------------------------------
NewCdDialog::~NewCdDialog(){
	delete factory;
	if(config)
		delete config;
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::init(){

	factory = new CdboDialogActionFactory(this, "NewCdDialogFactory");
	stillCreating = false;
	stillBurning = false;
	stillChecking = false;
	stillCreatingOnTheFly = false;
	config = 0;
	
	imageBrowseBtn->setPixmap( SmallIcon("fileopen") );
	
	///////////////////////////////////////////////////
	targetDevicePnl->setType(DriveInfoPnl::Target);
	targetDevicePnl->setUsrBtnTitle( i18n("&Erase"));
	/////////////////////////////////////////////////
	dialogCntPnl->setStartBtnTitle( i18n("&Create!"));
	QToolTip::add(dialogCntPnl->getStartBtn(), i18n( "Create!" ) );
	dialogCntPnl->resizeOutputViewColomns(80,550);
	/////////////////////////////////////////////////
	
	readOptions();
	initBtns();
	targetDevicePnl->closeTray();
	
	// connecting to the Drive Info Panel
	connect( targetDevicePnl->getDetectBtn(), SIGNAL( clicked() ), this, SLOT( detectDestSlot() ) );
	connect( targetDevicePnl->getUsrBtn(), SIGNAL( clicked() ), this, SLOT( eraseSlot() ) );
	
	// connecting to the Dialog Control Panel
	connect( dialogCntPnl->getStartBtn(), SIGNAL( clicked() ), this, SLOT( startBtnSlot() ) );
	connect( dialogCntPnl->getCancelBtn(), SIGNAL( clicked() ), this, SLOT( cancelSlot() ) );
	connect( dialogCntPnl->getSettingsBtn(), SIGNAL( clicked() ), this, SLOT( settingsSlot() ) );
	connect( dialogCntPnl->getQuitBtn(), SIGNAL( clicked() ), this, SLOT( quitSlot() ) );
	
	// connecting to the factory
	connect( factory, SIGNAL( processDone(bool) ), this, SLOT( taskDone(bool) ) );
	connect( factory, SIGNAL( failedToLunchProcess() ), this, SLOT( taskFailedToStart() ) );
	connect( factory, SIGNAL( processCancelled() ), this, SLOT( cancelledByUser() ) );
	

}
//---------------------------------------------------------------------------------------------
void NewCdDialog::saveOptions(){
	if(!config)
		return;
	//////////////////////////////////////////////////////////
     config->setGroup("Create Options");
     config->writeEntry("Type of Create", actionCmb->currentItem());
     config->writeEntry("Number of Copies", numberSpn->value());
     config->writeEntry("Remove Image", removeIsoChk->isChecked());
	
	speedPnl->saveOptions();
 	targetDevicePnl->saveOptions();
 	
 	config->sync();
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::readOptions(){
	saveOptions();
	if(config)
		delete config;
	config = new KConfig("cdbakeovenrc");
     ///////////////////////////////////////////////////////////////////
	config->setGroup("Create Options");
     	numberSpn->setValue(config->readNumEntry("Number of Copies", 0));
	removeIsoChk->setChecked(config->readBoolEntry("Remove Image", false));
	
     speedPnl->readOptions();
     targetDevicePnl->readOptions();
	
	config->setGroup("Default Settings");		
	QString tempDir = config->readEntry("Tmp Dir", "/tmp/");
	
	QString s = imageLbl->text();
	//if((s.isNull() || s == "") && createImage){
	if(createImage){
		config->setGroup("ISO Settings");	
		imageLbl->setText(tempDir + config->readEntry("Custom ISO Name", "cdboImage_<DATE>.iso"));
		QToolTip::add(imageLbl, imageLbl->text());
	}
}

//---------------------------------------------------------------------------------------------
void NewCdDialog::initBtns(){
	if(!createImage){
	//cerr << "*****************************************************\n";
       	if(targetDevicePnl->isReady()){
       		restructureActions(BURN);
       		
       		blockBtns(false);
       		//isoOptionsBtn->setEnabled(false);
       			
       		QString s = imageLbl->text();
       		if(!s.isNull() && s != ""){
       			dialogCntPnl->getStartBtn()->setEnabled(true);
       			isoPreviewBtn->setEnabled(true);					
       		}
       		else{
       			dialogCntPnl->getStartBtn()->setEnabled(false);
       			isoPreviewBtn->setEnabled(false);
       		}	
       		
       		blockActionBtns(false);
       		
       		dialogCntPnl->status(i18n("Ready"));
       	}
       	else{
       		blockBtns(true);
       		restructureActions(CREATE_ONLY);
       		dialogCntPnl->getCancelBtn()->setEnabled(false);
       		dialogCntPnl->status(i18n("No recording device!" ));
       	}
	}
	else{
		//cerr << "+++++++++++++++++++++++++++++++++++++++\n";
		blockBtns(false);
		
       	if(targetDevicePnl->isReady()){
       		
       		if(createImageOnly)
       			restructureActions(CREATE_ONLY);
       		else
       			restructureActions(CREATE);
       		
       		blockActionBtns(false);
       		dialogCntPnl->status(i18n("Ready"));
       	}
       	else{
       		restructureActions(CREATE_ONLY);
       		targetDevicePnl->blockBtns(true);
			speedPnl->setEnabled(false);
			
			blockActionBtns(true);
       		
       		dialogCntPnl->getCancelBtn()->setEnabled(false);
       		dialogCntPnl->status(i18n("No recording device!"));	
       	}
       	isoPreviewBtn->setEnabled(false);
       	isoOptionsBtn->setEnabled(true);
       	dialogCntPnl->getStartBtn()->setEnabled(true);
	}
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::blockActionBtns(bool yes){
	numberSpn->setEnabled(!yes);
	customBurnBtn->setEnabled(!yes);
	numOfCopiesLbl->setEnabled(!yes);
	removeIsoChk->setEnabled(!yes);
	imageBrowseBtn->setEnabled(!yes);
}
//----------------------------------------------------------------------------------------------
void NewCdDialog::blockBtns(bool yes) const{
	dialogCntPnl->getStartBtn()->setEnabled(!yes);
	dialogCntPnl->getCancelBtn()->setEnabled(yes);
	speedPnl->setEnabled(!yes);
	detailsPnl->setEnabled(!yes);
	targetDevicePnl->blockBtns(yes);
	if(stillCreating || stillChecking || stillBurning || stillCreatingOnTheFly){
		targetDevicePnl->getDetectBtn()->setEnabled(false);
		dialogCntPnl->getSettingsBtn()->setEnabled(false);
		dialogCntPnl->getDumpBtn()->setEnabled(false);
	}
	else{
		targetDevicePnl->getDetectBtn()->setEnabled(true);
		dialogCntPnl->getSettingsBtn()->setEnabled(true);		
		dialogCntPnl->getDumpBtn()->setEnabled(true);
	}
}
//----------------------------------------------------------------------------------------------
void NewCdDialog::restructureActions(int type){
	actionCmb->clear();
	switch(type){	
		case BURN:{
       			actionCmb->insertItem( i18n( "Burn" ) );
           		actionCmb->insertItem( i18n( "Test and Burn" ) );
           		actionCmb->insertItem( i18n( "'Dummy' Write" ) );
           		actionCmb->insertItem( i18n( "Add Session" ) );
           		actionCmb->insertItem( i18n( "Test and Add Session" ) );
           		actionCmb->insertItem( i18n( "'Dummy' Add Session" ) );
           	break;
           	}
    		case CREATE:{
           		actionCmb->insertItem( i18n( "Create Image and Burn" ) );
           		actionCmb->insertItem( i18n( "Create, Test and Burn" ) );
           		actionCmb->insertItem( i18n( "Write 'on-the-fly'" ) );
           		actionCmb->insertItem( i18n( "Test and Write 'on-the-fly'" ) );
           		actionCmb->insertItem( i18n( "'Dummy' Write 'on-the-fly'" ) );
           		actionCmb->insertItem( i18n( "Create Image Only" ) );
           	break;
    		}
    		case CREATE_ONLY:{
    			actionCmb->insertItem( i18n( "Create Image Only" ) );
    			return;
    		}
    	}
    	 ///////////////////////////////////////////////////////////////////
	config->setGroup("Create Options");
	int index = config->readNumEntry("Type of Create", 0);
	//if(index < 2)
     		actionCmb->setCurrentItem(index);
}
//--------------------- used by burn only ----------------------------------------
QString NewCdDialog::getActionType() const{
	int pos = actionCmb->currentItem();
	switch(pos){
		case 1:{
			if(copiesDone == 0)
				return "dummy";
			else
				return "burn";
		}
		case 2: {
			if(!createImage)
				return "dummy";
			else
				return "burn";	
		}
		case 3: {
			if(!createImage)
				return "append";
			else{
				if(copiesDone == 0)
					return "dummy";
				else
					return "burn";
				}
		}
		case 4: {
			if(!createImage){
				if(copiesDone == 0)
					return "dummy append";
				else
					return "append";
			}
			else
				return "dummy";
		}
		case 5: {
			if(!createImage)
				return "dummy append";
			else
				return "dummy";
		}
		default:
			return "burn";		
	}
	return "";
}
//----------------------------------------------------------------------------------------------
void NewCdDialog::isoBrowseSlot(){
	
	QString buff = imageLbl->text();
	if(!buff.isNull() && buff != "")
		buff = buff.left(buff.findRev("/", -2));
	else{
		config->setGroup("Default Settings");	
		buff = config->readEntry("Tmp Dir", QDir::homeDirPath());
	}	
	QString fileToOpen = KFileDialog::getOpenFileName( buff,
				"*.iso *.ISO *.raw *.RAW|ISO image files (*.iso, *.raw)\n*|All files",
				this,
				i18n("Open ISO Image..."));
	if(!fileToOpen.isNull() && fileToOpen != ""){
		imageLbl->setText( fileToOpen );
		QToolTip::add(imageLbl, fileToOpen);
		createImage = false;
		initBtns();
	}
}
//------------------------------------------------------------------------------------------
void NewCdDialog::isoPreviewSlot(){
	PreviewDialog *pd = new PreviewDialog(0, "pd");
	if(!pd->open(imageLbl->text(), true)){
		KMessageBox::error(this,
              i18n("Failed to mount " )+ imageLbl->text() + i18n(" "\
              "The image may be corrupt, or you do not have "\
              "enough privileges to use the 'mount' command."));
		return;
	}
	pd->exec();
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::isoOptionsSlot(){
	KShellProcess *cdboProc = new KShellProcess();
	*cdboProc << "kcmshell cdboisoopt";
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		kdDebug() << "Failed to start" << endl;
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::customBtnSlot(){
	KShellProcess *cdboProc = new KShellProcess();
	*cdboProc << "kcmshell cdboburnopt";
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		kdDebug()  << "Failed to start" << endl;
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::settingsSlot(){
	KShellProcess *cdboProc = new KShellProcess();
	*cdboProc << "kcmshell cdbodefaultopt";
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		kdDebug() << "Failed to start" << endl;
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::detectDestSlot(){
	KShellProcess *cdboProc = new KShellProcess();
	*cdboProc << "kcmshell cdbocdromdevices kcmdf";
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		kdDebug() << "Failed to start" << endl;
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::kcmshellDone(KProcess *proc){
	delete proc;
	readOptions();
	if(!(stillCreating || stillChecking || stillBurning || stillCreatingOnTheFly))
		initBtns();
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::eraseSlot(){

	//saveOptions();
	hide();
	EraseDialog *ed = new EraseDialog((QWidget *)parent(),"eraseD");
	ed->exec();
	delete ed;
	readOptions();
	initBtns();
	exec();
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::cancelSlot(){
	if((stillBurning || stillCreating || stillCreatingOnTheFly) && !confermExit())
		return;
	else{
		factory->killCurrentTask();
		if(stillCreating  && !stillCreatingOnTheFly){
			//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
			factory->removeOneFile(imageAddr);
			//imageLbl->setText(");
			//QToolTip::add(imageLbl, "");
		}
		
		if(stillBurning && !stillCreatingOnTheFly){
			output(CdboDialogBase::StatusNotOkMessage, "CD creation canceled!");
			if(removeIsoChk->isChecked() && createImage && !stillCreatingOnTheFly){
				int result = KMessageBox::warningContinueCancel(this,
        	   			i18n("Do you still want to remove the ISO image(s)?"),
                		i18n("Confirm Your Action"),
                		KStdGuiItem::yes());
               		if(result == KMessageBox::Continue)
					//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
					factory->removeOneFile(imageAddr);
					imageLbl->setText("");
					QToolTip::add(imageLbl, "");
			}
			//createImage = false;
		}
		else if(stillCreatingOnTheFly)
			output(CdboDialogBase::StatusNotOkMessage, i18n("CD creation canceled!"));
		else
			output(CdboDialogBase::StatusNotOkMessage, i18n("Image creation canceled!"));
		
		dialogCntPnl->stopForwardTimer();
		factory->resetSessionType();
		stillCreating = false;
		stillBurning = false;
		stillCreatingOnTheFly = false;
		blockBtns(false);
		readOptions();
		initBtns();
		status(i18n("Ready"));
	}
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::quitSlot(){
	if(stillBurning || stillCreating || stillCreatingOnTheFly){
		if(!confermExit()) return;
		else{
			//if(stillCreating)
			factory->killCurrentTask();
			if(stillCreating  && !stillCreatingOnTheFly){
				//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
				factory->removeOneFile(imageAddr);
				saveOptions();
				accept();
			}
			else if(stillBurning && !stillCreatingOnTheFly && createImage && removeIsoChk->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
        	   			i18n("Do you still want to remove the ISO image(s)?"),
                		i18n("Confirm your Action"),
                		KStdGuiItem::yes());
               		if(result == KMessageBox::Continue)
               			factory->removeOneFile(imageAddr);
					//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
				saveOptions();
				accept();
			}
			else{
				saveOptions();
				accept();
			}
		}
	}
	else{
		saveOptions();
		accept();
	}
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::closeEvent(QCloseEvent *e){
	if(stillBurning || stillCreating || stillCreatingOnTheFly){
		if(!confermExit()) e->ignore();
		else{
			factory->killCurrentTask();
			if(stillCreating  && !stillCreatingOnTheFly){
				//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
				factory->removeOneFile(imageAddr);
				e->accept();
			}
			else if(stillBurning && !stillCreatingOnTheFly && createImage && removeIsoChk->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
        	   			i18n("Do you still want to remove the ISO image(s)?"),
                		i18n("Confirm your Action"),
                		KStdGuiItem::yes());
               		if(result == KMessageBox::Continue)
               			factory->removeOneFile(imageAddr);
					//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
				e->accept();
			}
			else
				e->accept();
		}
	}
	else
		e->accept();
}

//---------------------------------------------------------------------------------------------
void NewCdDialog::keyPressEvent(QKeyEvent *e){
	if(e->key() == Key_Escape){
        	if(stillBurning || stillCreating || stillCreatingOnTheFly){
        		if(!confermExit()){
        			//e->ignore();
        			return;
        		}
        		else{
        			factory->killCurrentTask();
				if(stillCreating  && !stillCreatingOnTheFly){
					factory->removeOneFile(imageAddr);
					//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
					accept();
				}
				else if(stillBurning && !stillCreatingOnTheFly && createImage && removeIsoChk->isChecked()){
					int result = KMessageBox::warningContinueCancel(this,
                   	   			i18n("Do you still want to remove the ISO image(s)?"),
                           		i18n("Confirm your Action"),
                           		KStdGuiItem::yes());
                          if(result == KMessageBox::Continue)
           				factory->removeOneFile(imageAddr);
           				//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
           			accept();
           			}
     				else{
           			accept();
         			}
			}
        	}
        	accept();
	}
	if(e->key() == Key_F2){
		settingsSlot();
	}
}
//----------------------------------------------------------------------------------------------
bool NewCdDialog::confermExit(){
	if(stillChecking) return true;
	QString message;
	if(stillBurning || stillCreatingOnTheFly)
		message = i18n("Aborting now may damage your media, and/or even hang your system! Click \"Quit\" to abort.");
	else
		message = i18n("This will abort the image creation process. Aborting now may hang your system! Click \"Quit\" to abort.");
		
	int result = KMessageBox::warningContinueCancel(this,
	   message,
        i18n("This may hang your system!"),
        i18n("&Quit"));
    	switch(result) {
    		case KMessageBox::Continue:
    			/*if(stillBurning || stillCreatingOnTheFly)
				KMessageBox::error(this,
					"You've been WARNED!");*/
			return true;
		
		case KMessageBox::Cancel:
        		return false;
    	}
    	return false;
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::startBtnSlot(){
	saveOptions();
	dialogCntPnl->clearOutput();
	dialogCntPnl->startForwardTimer();
	
	createOnTheFly = false;
	if((actionCmb->currentItem() == 2 || actionCmb->currentItem() == 3 || actionCmb->currentItem() == 4) && createImage)
		createOnTheFly = true;
	
	
	if(createOnTheFly){
		if(fileList != 0)
			imageAddr = fileList->join(" ");
		else
			imageAddr = *isoFileMappings;
		startCreateOnTheFly();
	}
	else{
       	imageAddr = imageLbl->text();
       	
       	
       	if(createImage){
       		stillCreating = true;
       		
       		if(imageAddr.contains("<DATE>") != 0){		
       			QDate today = QDate::currentDate();
       			QTime now = QTime::currentTime();
       		
       			QString timeStamp = QString::number(today.month()) +
       		 		"_" + QString::number(today.day()) +
       		 		"_" + QString::number(now.hour()) +
       		 		"_" + QString::number(now.minute()) +
       		 		"_" + QString::number(now.second());
       			imageAddr.replace(QRegExp("<DATE>"), timeStamp);
       			imageLbl->setText(imageAddr);
       			QToolTip::add(imageLbl, imageAddr);
       						
       		}
       		if(actionCmb->currentItem() == 5){
       			createImageOnly = true;
       			if(fileList != 0)
					factory->createISO(fileList, imageAddr);
				else
					factory->createISO(isoFileMappings, imageAddr);
       		}
       		else if(actionCmb->currentItem() == 2 || actionCmb->currentItem() == 3 || actionCmb->currentItem() == 4){
       			if(fileList != 0)
					imageAddr = fileList->join(" ");
				else
					imageAddr = *isoFileMappings;
       			stillCreatingOnTheFly = true;
				
				startCreateOnTheFly();
       		}
       		else{
       			if(fileList != 0)
					factory->createISO(fileList, imageAddr);
				else
					factory->createISO(isoFileMappings, imageAddr);
       		}
       	}
       	else
       		startBurn();
	}
}	
//---------------------------------------------------------------------------------------------
void NewCdDialog::startCreateOnTheFly(){
	targetDevicePnl->closeTray();
	
	stillCreatingOnTheFly = true;
	
	copiesDone = 0;
	
	if(actionCmb->currentItem() == 2)
		copiesWanted = numberSpn->value();
	else if(actionCmb->currentItem() ==3)
		copiesWanted = numberSpn->value() + 1;
	else
		copiesWanted = 0;
	
	/////////////////////////////////////////			
	config->setGroup("Recording Options");
	stillChecking = config->readBoolEntry("Check Drive First", false);
	if(stillChecking)
		factory->checkDrive();
	else{
       	if(fileList != 0)
			factory->createCdOnTheFly(fileList);
		else
			factory->createCdOnTheFly(isoFileMappings);
       }
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::startBurn(){
	targetDevicePnl->closeTray();
	
	stillBurning = true;
	
	copiesDone = 0;
	if(actionCmb->currentItem() == 2 || actionCmb->currentItem() == 5)
		copiesWanted = 0;
	else if(actionCmb->currentItem() == 1 || actionCmb->currentItem() == 4)
		copiesWanted = numberSpn->value() + 1;
	else
		copiesWanted = numberSpn->value();
	
	/////////////////////////////////////////			
	config->setGroup("Recording Options");
	stillChecking = config->readBoolEntry("Check Drive First", false);
	if(stillChecking)
		factory->checkDrive();
	else
		factory->burn(imageAddr);
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::taskDone(bool success){
	if(!success){
		dialogCntPnl->stopForwardTimer();
		if(stillCreating && !stillCreatingOnTheFly){
			factory->removeOneFile(imageAddr);
			//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
			//imageLbl->setText("");
			//QToolTip::add(imageLbl, "");
		}
		
		stillCreating = false;
		if(stillBurning ){
			stillBurning = false;
			if(createImage && !stillCreatingOnTheFly && removeIsoChk->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
        	   				i18n("Do you still want to remove the temporary image?"),
                			i18n("Confirm your Action"),
                			KStdGuiItem::yes());
               		if(result == KMessageBox::Continue){
					factory->removeOneFile(imageAddr);
					//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
					imageLbl->setText("");
					QToolTip::add(imageLbl, "");
				}
			}
			//createImage = false;
			stillChecking = false;
		}
		
		if(!stillCreatingOnTheFly)
			readOptions();
		stillCreatingOnTheFly = false;
		initBtns();
		factory->resetSessionType();
		return;
	}
	
	if(stillCreating){
		stillCreating = false;
		createImage = false;
		if(!createImageOnly){	
			imageLbl->setText(imageAddr);
			startBurn();
		}
		else{	
			//createImage = false;
			createImageOnly = false;
			dialogCntPnl->stopForwardTimer();
			factory->resetSessionType();
			if(!stillCreatingOnTheFly)
				readOptions();
			stillCreatingOnTheFly = false;
			initBtns();
			return;
		}
	}
	else if(stillChecking){
		stillChecking = false;
     	/////////////////////////////////////////			
      	config->setGroup("Recording Options");
		if(config->readBoolEntry("Eject Media At End", true))
			targetDevicePnl->setEjected();
		if(createOnTheFly){
			if(fileList != 0)
				factory->createCdOnTheFly(fileList);
			else
				factory->createCdOnTheFly(isoFileMappings);
       	}
       	else
     			factory->burn(imageAddr);
	}
	else if(stillBurning || stillCreatingOnTheFly){
		copiesDone++;
  		if(copiesDone < copiesWanted){
			int fix = 0;
			int ci = actionCmb->currentItem();
     		if( (createImage && (ci == 1 || ci == 3 || ci == 4)) ||
     				(!createImage && (ci == 1 || ci == 2 || ci == 4 || ci == 5)) ){
				if(copiesDone == 1){
					output(CdboDialogBase::StatusOkMessage, "Dummy run completed successfully!");
					/////////////////////////////////////
					
					int result = KMessageBox::questionYesNo(this,
						i18n("Dummy run completed successfully! Continue with burn?"),
        					i18n("Continue with Burn?"));
					switch(result) {
    						case KMessageBox::No:{
    						///////////////////////=====================
							dialogCntPnl->stopForwardTimer();
							stillBurning = false;
							//createImage = false;
							if(!stillCreatingOnTheFly && createImage && removeIsoChk->isChecked()){
								int result = KMessageBox::warningContinueCancel(this,
        	   							i18n("Do you still want to remove temporary image(s)?"),
                						i18n("Confirm your Action"),
                						KStdGuiItem::yes());
               					if(result == KMessageBox::Continue)
								cleanUp();
							}
							createOnTheFly = false;
							blockBtns(false);
							factory->resetSessionType();
							if(!stillCreatingOnTheFly)
								readOptions();
							stillCreatingOnTheFly = false;
							initBtns();
							return;
						}///////////////////////=====================
						case KMessageBox::Yes:{
							if(stillCreatingOnTheFly){
       							if(fileList != 0)
									factory->createCdOnTheFly(fileList);
								else
									factory->createCdOnTheFly(isoFileMappings);
      					 		}
							else
								factory->burn(imageAddr);
							return;	
						}
					}
				}
				else
					fix = 1;
			}
			output(CdboDialogBase::StatusOkMessage, "" + QString::number(copiesDone - fix) +
				" of " + QString::number(copiesWanted - fix) +
				" burned successfully!");
			KMessageBox::information(this,
				"" + QString::number(copiesDone - fix) + " of " +
				QString::number(copiesWanted - fix) + "  wanted copies are done!" \
	   			"Please insert next CD-R(W) and click 'OK'.",
	   			i18n("Please insert next CD-R(W)"));
	   	
	   		/////////////////////////////////////////			
			config->setGroup("Recording Options");
     			if(config->readBoolEntry("Eject Media At End", true))
     				targetDevicePnl->setEjected();
     			
     			if(stillCreatingOnTheFly){
                    	if(fileList != 0)
             			factory->createCdOnTheFly(fileList);
             		else
             			factory->createCdOnTheFly(isoFileMappings);
                    }
     			else
	  			factory->burn(imageAddr);
		}
		else{
			dialogCntPnl->stopForwardTimer();
			stillBurning = false;
			//createImage = false;
			createOnTheFly = false;
			if(actionCmb->currentItem() == 5)
				output(CdboDialogBase::StatusOkMessage, i18n("Dummy run completed successfully!"));
			else
				output(CdboDialogBase::StatusOkMessage, i18n("Operation completed successfully!"));
				
			if(removeIsoChk->isChecked())
				cleanUp();
			blockBtns(false);
			factory->resetSessionType();
			if(!stillCreatingOnTheFly)
				readOptions();
			stillCreatingOnTheFly = false;
			initBtns();
		}
	}
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::taskFailedToStart(){
	dialogCntPnl->stopForwardTimer();
	stillCreating = false;
	
	
	if(stillBurning){
		stillBurning = false;
		if(!stillCreatingOnTheFly && createImage && removeIsoChk->isChecked()){
			int result = KMessageBox::warningContinueCancel(this,
        	   				i18n("Do you still want to remove temporary image(s)?"),
                			i18n("Confirm your Action"),
                			KStdGuiItem::yes());
               	if(result == KMessageBox::Continue)
				cleanUp();
		}
		//createImage = false;
	}
	if(!stillCreatingOnTheFly)
		readOptions();
	stillCreatingOnTheFly = false;
	initBtns();
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::cancelledByUser(){
	dialogCntPnl->stopForwardTimer();
	stillCreating = false;
	if(!stillCreatingOnTheFly)
		readOptions();
	stillCreatingOnTheFly = false;
	initBtns();
	stillChecking = false;
	stillBurning = false;
}
//---------------------------------------------------------------------------------------------
void NewCdDialog::cleanUp(){
	
	if(stillCreatingOnTheFly)
		return;
	else
		factory->removeOneFile(imageAddr);
		//factory->removeTmpImage(imageAddr,imageAddr.left(imageAddr.findRev("/", -2)));
	/*else{
		QStringList flist = *fileList;
		for(int i = 0; i < (int)flist.count(); i++)
			factory->removeOneFile(flist[i]);
			//factory->removeTmpImage(flist[i],flist[i].left(flist[i].findRev("/", -2)));
	
	}*/
	imageLbl->setText("""");
	QToolTip::add(imageLbl, """");
}
