/***************************************************************************
                          CdCopyDialog.cpp  -  description
                             -------------------
    begin                : Sat May 5 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 <qfile.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 <kiconloader.h>
#include <kprocess.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kconfig.h>
#include <kurl.h>
#include <kdirsize.h>
#include <kapplication.h>

#include "CdCopyDialogBase.h"
#include "CdCopyDialog.h"
#include "CdCopyDialog.moc"
#include "EraseDialog.h"
#include "PreviewDialog.h"
#include "../audio/CdboCddaView.h"

#define TEST_AND_COPY 1
#define COPY 0
#define DUMMY_COPY 2
#define ON_THE_FLY_COPY 3

//---------------------------------------------------------------------------------------------
CdCopyDialog::CdCopyDialog(QWidget *parent, const char *name ) :
	CdCopyDialogBase(parent,name,true),
	CdboDialogBase(CdboDialogBase::CdCopyDialogType){
	//////////////
	factory = new CdboDialogActionFactory(this, "CdCopyDialogFactory");	
	stillCopying = false;
	stillChecking = false;
	stillReading = false;
	remindedAlready = false;
	
	///////////////////////////////////////////////////
	targetDevicePnl->setType(DriveInfoPnl::Target);
	targetDevicePnl->setUsrBtnTitle(i18n("&Erase"));
	/////////////////////////////////////////////////
	srcDevicePnl->setType(DriveInfoPnl::Source);
	srcDevicePnl->setUsrBtnTitle(i18n("&Preview"));
	////////////////////////////////////////////////
	dialogCntPnl->setStartBtnTitle(i18n("&Copy!"));
	QToolTip::add(dialogCntPnl->getStartBtn(), i18n( "Start copying!" ) );
	dialogCntPnl->resizeOutputViewColomns(80,548);
	/////////////////////////////////////////////////
	
	config = 0;
	readOptions();
	initBtns();
	targetDevicePnl->closeTray();
	///////////////////////////////////////////////
	trackView->setUser(this);
	trackView->resizeTrackViewColomns(55,55,330);
	///////////////////////////////////////////
	
	// 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 Src Drive Info Panel
	connect( srcDevicePnl->getDetectBtn(), SIGNAL( clicked() ), this, SLOT( detectDestSlot() ) );
	connect( srcDevicePnl->getUsrBtn(), SIGNAL( clicked() ), this, SLOT( previewSlot() ) );
	connect( srcDevicePnl, SIGNAL( trayEjected() ), trackView, SLOT( invalidate() ) );
	
	// 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( tmpCheckProcessDone(bool) ), this, SLOT( tmpChecked(bool) ) );

}
//---------------------------------------------------------------------------------------------
CdCopyDialog::~CdCopyDialog(){
	delete factory;
	if(config)
		delete config;
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::readOptions(){
	saveOptions();
	if(config)
		delete config;
	config = new KConfig("cdbakeovenrc");
	
	////////////////////////////////////////////////	
     config->setGroup("Default Settings");		
	tempDir = config->readEntry("Tmp Dir", "");
	
	removeTempBtn->setChecked(config->readBoolEntry("Remove Tmp File", true));
	
	checkTmpSize = config->readBoolEntry("Check Tmp Size", true);
	minTmpSize = config->readNumEntry("Minimum Tmp Size", 650);
	
	
	///////////////////////////////////////////////////////////////////
	config->setGroup("Copy Options");
     actionCmb->setCurrentItem(config->readNumEntry("Type of Copy", 0));
     numberSpn->setValue( config->readNumEntry("Number of Copies", 0) );
	if(config->readBoolEntry("Data CD", true)){
		dataSlot();
		dataRBtn->setChecked(true);
	}
	else{
		musicSlot();
		musicRBtn->setChecked(true);
	}
	
	speedPnl->readOptions();
	targetDevicePnl->readOptions();
	srcDevicePnl->readOptions();
	trackView->readOptions();
	trackView->setDevice(srcDevicePnl->getDriveName());
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::saveOptions(){
	if(!config)
		return;
	//////////////////////////////////////////////////////////
     config->setGroup("Copy Options");
     config->writeEntry("Type of Copy", actionCmb->currentItem());
     config->writeEntry("Number of Copies", numberSpn->value());
     config->writeEntry("Data CD", dataRBtn->isChecked());

     ////////////////////////////////////////////////////////////////////
     config->setGroup("Default Settings");

	config->writeEntry("Remove Tmp File", removeTempBtn->isChecked());
	
	speedPnl->saveOptions();
 	targetDevicePnl->saveOptions();
 	srcDevicePnl->saveOptions();
 	trackView->saveOptions();
 	
 	config->sync();
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::initBtns(){
	if(targetDevicePnl->isReady()){
		
		srcDevicePnl->closeTray();
		blockBtns(false);
		dialogCntPnl->status(i18n("Ready"));
	}
	else{
		blockBtns(true);
		dialogCntPnl->getCancelBtn()->setEnabled(false);
		if(srcDevicePnl->isReady()){
			srcDevicePnl->blockBtns(false);
			srcDevicePnl->closeTray();
		}
		dialogCntPnl->status(i18n("No recording device configured."));
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::blockBtns(bool yes) const{
	dialogCntPnl->getStartBtn()->setEnabled(!yes);
	dialogCntPnl->getCancelBtn()->setEnabled(yes);
	trackView->setEnabled(!yes);
	detailsFrm->setEnabled(!yes);
	targetDevicePnl->blockBtns(yes);
	srcDevicePnl->blockBtns(yes);
	if(stillReading || stillChecking || stillCopying){
		targetDevicePnl->getDetectBtn()->setEnabled(false);
		srcDevicePnl->getDetectBtn()->setEnabled(false);
		dialogCntPnl->getSettingsBtn()->setEnabled(false);
		dialogCntPnl->getDumpBtn()->setEnabled(false);
	}
	else{
		targetDevicePnl->getDetectBtn()->setEnabled(true);
		srcDevicePnl->getDetectBtn()->setEnabled(true);
		dialogCntPnl->getSettingsBtn()->setEnabled(true);
		dialogCntPnl->getDumpBtn()->setEnabled(true);
	}
}
//======================================================
void CdCopyDialog::musicSlot(){
	if(config)
		delete config;
	config = new KConfig("cdbakeovenrc");
	config->setGroup("Recording Options");
	readOnlyChk->setChecked(config->readBoolEntry("Fixate CD", true));
	config->setGroup("Copy Options");
	readOnlyChk->setText( i18n( "Finalize CD" ) );
	QToolTip::add(  readOnlyChk, i18n( "Fixate (Finalize) the disk after writing the tracks. This may be used to create an audio disk in steps. You can fixate this disk later with the 'Fixate Dialog'." ) );
	disconnect( readOnlyChk, SIGNAL( clicked() ), this, SLOT( readOnlyChkSlot() ) );
	connect( readOnlyChk, SIGNAL( clicked() ), this, SLOT( fixateChkSlot() ) );
	

	audioTb->setEnabled(true);
	outputTypeChk->setEnabled(false);
	optionsBtn->setEnabled(true);
	srcDevicePnl->setUsrBtnTitle(i18n("Scan &Tracks"));
	//trackView->setDevice(srcDevicePnl->getDriveName());
	if(!remindedAlready){
		output(CdboDialogBase::InfoMessage,
  			 i18n("You have chosen Audio (Music) CD type as the source for copying."));
		output(CdboDialogBase::InfoMessage,
  				i18n("You will need to scan the device if you want to pick the individual tracks."));
		remindedAlready = true;
	}
}
//======================================================
void CdCopyDialog::dataSlot(){
	if(config)
		delete config;
	config = new KConfig("cdbakeovenrc");
	config->setGroup("Copy Options");
	readOnlyChk->setChecked(config->readBoolEntry("Read Only Data", false));
	readOnlyChk->setText( i18n( "Read Only" ) );
	QToolTip::add(  readOnlyChk, i18n( "Read only and don't burn anything" ) );
	disconnect( readOnlyChk, SIGNAL( clicked() ), this, SLOT( fixateChkSlot() ) );
	connect( readOnlyChk, SIGNAL( clicked() ), this, SLOT( readOnlyChkSlot() ) );
	
	audioTb->setEnabled(false);
	outputTypeChk->setEnabled(true);
	optionsBtn->setEnabled(false);
	srcDevicePnl->setUsrBtnTitle(i18n("&Preview"));
	trackView->invalidate();
}
//------------------------------------------------------------------------------------------
void CdCopyDialog::readOnlyChkSlot() {
	if(config)
		delete config;
	config = new KConfig("cdbakeovenrc");
	config->setGroup("Copy Options");
	config->writeEntry("Read Only Data", readOnlyChk->isChecked());
}
//------------------------------------------------------------------------------------------
void CdCopyDialog::fixateChkSlot() {
	if(config)
		delete config;
	config = new KConfig("cdbakeovenrc");
	config->setGroup("Recording Options");
	config->writeEntry("Fixate CD", readOnlyChk->isChecked());
	config->setGroup("Copy Options");
}
//------------------------------------------------------------------------------------------
void CdCopyDialog::previewSlot(){
	if(dataRBtn->isChecked()){
       	PreviewDialog *pd = new PreviewDialog((QWidget *)parent(), "pd");
       	if(!pd->open(srcDevicePnl->getDriveName())){
       		KMessageBox::error(this,
                     i18n("Failed to mount %1. Make sure you have enough privileges to perform this action.").arg(targetDevicePnl->getDriveName()));
       		return;
       	}
		pd->exec();
	}
	else{///////it's scan tracks for this one
		trackView->invalidate();
		dialogCntPnl->clearOutput();
		trackView->load(srcDevicePnl->getDriveName());
		deatilesTab->showAudioTab();
		
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::customBtnSlot(){
	KShellProcess *cdboProc = new KShellProcess();
	*cdboProc << "kcmshell cdboburnopt";
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		cerr << "Failed to start\n\n";
}
//----------------------------------------------------------------------------------------------
void CdCopyDialog::readOptionsBtnSlot(){
	if(dataRBtn->isChecked())
		customBtnSlot();
	else{
		KShellProcess *cdboProc = new KShellProcess();
		*cdboProc << "kcmshell cdboaudioopt";
		connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
		if(!cdboProc->start(KProcess::NotifyOnExit))
			cerr << "Failed to start\n\n";
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::detectDestSlot(){
	KShellProcess *cdboProc = new KShellProcess();
	*cdboProc << "kcmshell cdbocdromdevices kcmdf";
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		cerr << "Failed to start\n\n";
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::settingsSlot(){
	KShellProcess *cdboProc = new KShellProcess();
	*cdboProc << "kcmshell cdbodefaultopt";
	connect(cdboProc, SIGNAL(processExited(KProcess*)), this, SLOT(kcmshellDone(KProcess*)));
	if(!cdboProc->start(KProcess::NotifyOnExit))
		cerr << "Failed to start\n\n";
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::kcmshellDone(KProcess *proc){
	delete proc;
	readOptions();
	if(!(stillReading || stillChecking || stillCopying))
		initBtns();
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::eraseSlot(){
	saveOptions();
	EraseDialog *ed = new EraseDialog((QWidget *)parent(),"eraseD");
	hide();
	ed->exec();
	delete ed;
	readOptions();
	initBtns();
	exec();
}
//---------------------------------------------------------------------------------------------
QString CdCopyDialog::getActionType() const{
	if(actionCmb->currentItem()  == DUMMY_COPY){	
		return "dummy";
	}
	else if(actionCmb->currentItem() == TEST_AND_COPY && copiesDone == 1)
		return "dummy";
	else
		return "burn";
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::startBtnSlot(){
	saveOptions();
	trackView->stop();
	dialogCntPnl->clearOutput();
	dialogCntPnl->startForwardTimer();
	
	imageAddr = "";
	
	copiesDone = 1;
	
	if(getCopyType() == DUMMY_COPY)
		copiesDone = copiesWanted;
	else if(getCopyType() == TEST_AND_COPY)
		copiesWanted = numberSpn->value() + 1;
	else
		copiesWanted = numberSpn->value();

	if(getCopyType() == ON_THE_FLY_COPY){
		//if audio or same device - no good!
		if(srcDevicePnl->getDriveName() == targetDevicePnl->getDriveName()){
			KMessageBox::error(this,
				i18n("You cannot 'copy on the fly' using the same device! "\
				"Please choose another action."));
			dialogCntPnl->stopForwardTimer();
			return;
		}
		if(!dataRBtn->isChecked()){
			KMessageBox::error(this,
				i18n("You cannot 'copy on the fly' an audio CD! "\
				"Please choose another action."));
			dialogCntPnl->stopForwardTimer();
			return;
		}
		///start check or reading		
		config->setGroup("Recording Options");
		stillChecking = config->readBoolEntry("Check Drive First", false);
		if(stillChecking)
			factory->checkDrive();		
		else
			startCopyProcess();
	}
	else{
		stillChecking = true;
		//get size of image when ever possible
		KURL url(KIO::findDeviceMountPoint(srcDevicePnl->getDriveName()));
		int iBuff = (int)(KDirSize::dirSize(url) / 1024 / 1024);
		//if image is bigger then minimum size, make it minimum
		if(iBuff > minTmpSize)
			minTmpSize = iBuff;
		if(!factory->checkTmp(tempDir, minTmpSize)) {
			KMessageBox::error(this,
				i18n("You must choose a valid temporary directory!"));
		}
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::tmpChecked(bool success){
	if(!stillChecking) return;

	if(checkTmpSize && !success){
		KMessageBox::error(this,
			i18n("The chosen directory does not have enough space available " \
			"for storing the disk image. Please choose another location."));
		stillChecking = false;
		dialogCntPnl->stopForwardTimer();
		return;
	}
	else{	
		config->setGroup("Recording Options");
		stillChecking = config->readBoolEntry("Check Drive First", false);
		if(stillChecking){
			factory->checkDrive();
		}
		else{
			startCopyProcess();
		}
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::taskDone(bool success){
	if(!success){
		output(CdboDialogBase::StatusNotOkMessage, i18n("Copy process failed!"));
		dialogCntPnl->stopForwardTimer();
		config->setGroup("Recording Options");
		bool ejectAtEnd = config->readBoolEntry("Eject Media At End", true);
		
		if(stillReading){
			cleanUp();
			if(ejectAtEnd)
				srcDevicePnl->eject();
		}
		if(stillCopying){
			if(ejectAtEnd)
				targetDevicePnl->eject();
			if(getCopyType() != ON_THE_FLY_COPY && removeTempBtn->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
	   				i18n("Do you still want to remove temporary image(s)?"),
        				i18n("Confirm your Action"),
        				i18n("Yes"));
       			if(result == KMessageBox::Continue)
					cleanUp();
			}
		}
		stillCopying = false;
		stillReading = false;
		stillChecking = false;
		blockBtns(false);
		return;
	}
	/// if success /////////////////////////////////////////////////////
	if(stillChecking){
     		stillChecking = false;
     		//dialogCntPnl->startForwardTimer();
     		startCopyProcess();
     		return;
	}
	else if(stillReading){
		stillReading = false;
		config->setGroup("Recording Options");
    		if(config->readBoolEntry("Eject Media At End", true))
			srcDevicePnl->eject();
		if(readOnly){
			output(CdboDialogBase::StatusOkMessage, i18n("Read operation completed successfully!"));
     			if(removeTempBtn->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
	   				i18n("Are you sure you want to remove the output image?"),
        				i18n("Confirm your Action"),
        				i18n("Yes"));
       			if(result == KMessageBox::Continue)
					cleanUp();
			}
			dialogCntPnl->stopForwardTimer();
			blockBtns(false);
			status(i18n("Ready."));
			return;
		}
		if(srcDevicePnl->getDriveName() == targetDevicePnl->getDriveName()){
			KMessageBox::information(this, i18n("Please insert CD-R(W) into %1 and click 'OK'.").arg(srcDevicePnl->getDriveName()),
	   			i18n("Please Insert CD-R(W)"));
		}
     	doCopy();
     	return;
 	}	
	else if(copiesDone < copiesWanted){
		copiesDone++;
		int fix = 0;
      	if(getCopyType() == TEST_AND_COPY){
 			if(copiesDone == 2){
 				output(CdboDialogBase::StatusOkMessage, i18n("Dummy run completed successfully!"));
 				/////////////////////////////////////
				int result = KMessageBox::questionYesNo(this,
						i18n("Dummy run completed successfully! Continue with burn?"),
        					i18n("Continue with Burn?"),
        					i18n("&Yes"),
        					i18n("&No"));
				switch(result) {
    					case KMessageBox::No:{//
    						config->setGroup("Recording Options");
     					if(config->readBoolEntry("Eject Media At End", true))
     						targetDevicePnl->setEjected();
						if(removeTempBtn->isChecked()){
							int result = KMessageBox::warningContinueCancel(this,
	   							i18n("Do you still want to remove temporary image(s)?"),
        							i18n("Confirm your Action"),
        							i18n("Yes"));
       						if(result == KMessageBox::Continue)
								cleanUp();
						}
						dialogCntPnl->stopForwardTimer();
						stillCopying = false;
						stillReading = false;
						stillChecking = false;
						blockBtns(false);
						status(i18n("Ready."));
						return;
    					}///////////////////////=====================
					case KMessageBox::Yes:{
						if(!dataRBtn->isChecked())
							imageAddr = "'" + tmpList.join("' '");
						factory->burn(imageAddr + "'", !dataRBtn->isChecked());
 						return;	
 					}
 				}
 			}
 			else
 				fix = 1;
 		}
      	output(CdboDialogBase::StatusOkMessage, "" + QString::number(copiesDone - fix) +
 			i18n(" of " )+ QString::number(copiesWanted - fix) +
 			i18n(" copied successfully!"));
 		
 		KMessageBox::information(this,
 			"" + QString::number(copiesDone - fix) + i18n(" of ") +
 			QString::number(copiesWanted - fix) + i18n(" requested copies are done! " \
 	   		"Please Insert the next CD-R(W) and Click 'OK'."),
 	   		i18n("Please insert next CD-R(W)"));
      	qApp->processEvents();
      	//targetDevicePnl->closeTray();
      		targetDevicePnl->closeTrayAndWait();
		if(!dataRBtn->isChecked())
			imageAddr = "'" + tmpList.join("' '");
	   	factory->burn(imageAddr + "'", !dataRBtn->isChecked());
	}
	else{
		/////////////////////////////////////////			
		config->setGroup("Recording Options");
     	if(config->readBoolEntry("Eject Media At End", true))
     		targetDevicePnl->setEjected();
		
		if(getCopyType() == DUMMY_COPY)
			output(CdboDialogBase::StatusOkMessage, i18n("Dummy run completed successfully!"));
		else
			output(CdboDialogBase::StatusOkMessage, i18n("Copy process completed successfully!"));
		
		if(removeTempBtn->isChecked())
			cleanUp();
		dialogCntPnl->stopForwardTimer();
		stillCopying = false;
		stillReading = false;
		stillChecking = false;
		blockBtns(false);
		
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::taskFailedToStart(){
	output(CdboDialogBase::StatusNotOkMessage, i18n("Copy process failed!"));
	dialogCntPnl->stopForwardTimer();
	stillCopying = false;
	stillReading = false;
	stillChecking = false;
	blockBtns(false);
}
//------------------------------------------------------------------------------------
void CdCopyDialog::startCopyProcess(){
	//srcDevicePnl->closeTray();
	//if(srcDevicePnl->isEjected()) srcDevicePnl->closeTrayAndWait();	
	//cerr << "CLOSED\n";
	if(getCopyType() == ON_THE_FLY_COPY){
		//targetDevicePnl->closeTray();
		targetDevicePnl->closeTrayAndWait();	
		imageAddr = srcDevicePnl->getDriveName();
		stillCopying = true;
		if(!dataRBtn->isChecked())
			imageAddr = "'" + tmpList.join("' '");
     		factory->burn(imageAddr + "'");
		return;
	}
	//////////
	QDate today = QDate::currentDate();
	QTime now = QTime::currentTime();
	imageAddr = tempDir + "cdboImage_" + QString::number(today.month()) +
		 "_" + QString::number(today.day()) +
		 "_" + QString::number(now.hour()) +
		 "_" + QString::number(now.minute()) +
		 "_" + QString::number(now.second());
	
	stillReading = true;
	if(dataRBtn->isChecked()){
		readOnly = readOnlyChk->isChecked();
		factory->readData(srcDevicePnl->getDriveName(), &imageAddr);
		
	}
	else{
		///////////////////////////////////////////////////////
		//config->setGroup("Audio Read Options");
		readOnly = false;//////////////////////////////////////////////////
		stillReading = true;
		//output(CdboDialogBase::InfoMessage, "This CD was not fxated.");
		//=============================================================================
		QStringList* tracks = trackView->getPickedTracks();
		if(tracks && tracks->count() == 0){
			output(CdboDialogBase::ErrorMessage, i18n("0 tracks selected! There is nothing to copy."));
			
			dialogCntPnl->stopForwardTimer();
			status(i18n("Ready."));
			stillCopying = false;
			stillReading = false;
			stillChecking = false;
			blockBtns(false);
			return;
		}
		tmpList.clear();
		factory->readAudio(srcDevicePnl->getDriveName(), tracks, &tmpList);
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::doCopy(){
	//targetDevicePnl->closeTray();
	targetDevicePnl->closeTrayAndWait();	
	stillCopying = true;
	if(!dataRBtn->isChecked())
		imageAddr = "'" + tmpList.join("' '");
     factory->burn(imageAddr + "'", !dataRBtn->isChecked());
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::cancelSlot(){
	if(confermExit()){
		factory->killCurrentTask();
		if(stillCopying){
			output(CdboDialogBase::StatusNotOkMessage, i18n("Copy process canceled,"));
			if(getCopyType() != ON_THE_FLY_COPY && removeTempBtn->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
	   				i18n("Do you still want to remove temporary image(s)?"),
        				i18n("Confirm your Action"),
        				i18n("Yes"));
       			if(result == KMessageBox::Continue)
					cleanUp();
			}
		}
		else if(stillReading){
			output(CdboDialogBase::StatusNotOkMessage, i18n("Read process canceled."));
			cleanUp();
		}
		dialogCntPnl->stopForwardTimer();
		status(i18n("Ready."));
		stillCopying = false;
		stillReading = false;
		stillChecking = false;
		blockBtns(false);	
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::quitSlot(){
	
	if(stillCopying || stillReading){
		if(!confermExit()) return;
		else{
			trackView->invalidate();
			factory->killCurrentTask();
			if(stillReading)
				cleanUp();
			
			if(stillCopying && getCopyType() != ON_THE_FLY_COPY && removeTempBtn->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
	   				i18n("Do you still want to remove temporary image(s)?"),
        				i18n("Confirm your Action"),
        				i18n("Yes"));
       			if(result == KMessageBox::Continue)
					cleanUp();
			}
			saveOptions();
			accept();
		}
	}
	else{	
		saveOptions();
		accept();
	}
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::closeEvent(QCloseEvent *e){
	
	if(stillCopying || stillReading){
		if(!confermExit()) e->ignore();
		else{
			trackView->invalidate();
			factory->killCurrentTask();
			if(stillReading)
				cleanUp();
			
			if(stillCopying && getCopyType() != ON_THE_FLY_COPY && removeTempBtn->isChecked()){
				int result = KMessageBox::warningContinueCancel(this,
	   				i18n("Do you still want to remove temporary image(s)?"),
        				i18n("Confirm your Action"),
        				i18n("Yes"));
       			if(result == KMessageBox::Continue)
					cleanUp();
			}
			e->accept();
		}
	}
	else
		e->accept();
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::keyPressEvent(QKeyEvent *e){
	if(e->key() == Key_Escape){
        	
        	if(stillCopying || stillReading){
        		if(!confermExit()) return;
        		else{
				trackView->invalidate();
        			factory->killCurrentTask();
        			if(stillReading)
        				cleanUp();
        			
        			if(stillCopying && getCopyType() != ON_THE_FLY_COPY && removeTempBtn->isChecked()){
        				int result = KMessageBox::warningContinueCancel(this,
        	   				i18n("Do you still want to remove temporary image(s)?"),
                			i18n("Confirm your Action"),
                			i18n("Yes"));
               			if(result == KMessageBox::Continue)
        					cleanUp();
        			}
        		}
        	}
        	accept();
	}
	if(e->key() == Key_F2){
		settingsSlot();
	}
}
//---------------------------------------------------------------------------------------------
bool CdCopyDialog::confermExit(){
	if(!stillCopying && !stillReading) return true;
	QString message;
	if(stillCopying)
		message = i18n("Aborting now may damage your media, and/or even hang your system!");
	else
		message = i18n("This will abort the read process. Aborting now may hang your system!");
	int result = KMessageBox::warningContinueCancel(this,
	   message,
        i18n("This may hang your system!"),
        i18n("Quit"));
    	switch(result) {
    		case KMessageBox::Continue:{
    			/*KMessageBox::error(this,
				"You've been WARNED!");*/
			return true;
		}
		case KMessageBox::Cancel:
        		return false;
    	}
    	return false;
}
//---------------------------------------------------------------------------------------------
void CdCopyDialog::cleanUp(){
	if(tmpList.count() == 0){
		factory->removeTmpImage(imageAddr,tempDir);
		return;
	}
	QString buff;
	for(int i = 0; i < tmpList.count(); i++){
		buff =tmpList[i];
		factory->removeOneFile(buff);
		factory->removeOneFile( buff.left(buff.find(".")) + ".inf" );
		
	}
}
