/***************************************************************************
                          DataCompilationTreeView.cpp  -  description
                             -------------------
    begin                : Mon Nov 19 2001
    copyright            : (C) 2001 by Alex Podolsky
    email                : alexpod@users.sf.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>
// QT includes
#include <qdir.h>
#include <qstringlist.h>
#include <qcheckbox.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qclipboard.h>
#include <qapp.h>
#include <qfileinfo.h>
#include <qdragobject.h>
#include <qevent.h>
#include <qregexp.h>





// KDE includes
#include <kurl.h>
#include <klocale.h>
#include <kconfig.h>
#include <kapplication.h>
#include <kio/job.h>
#include <kpropsdlg.h>
#include <kopenwith.h>
#include <kio/netaccess.h>
#include <kio/jobclasses.h>
#include <kfileview.h>
#include <kmessagebox.h>
#include <klistview.h>
#include <kmimemagic.h>
//#include <kdirsize.h>
#include <kfiledialog.h>
#include <kiconloader.h>

// CDBO includes
#include "DataCompilationTreeView.h"
#include "DataCompilationTreeView.moc"
#include "CdboFileItem.h"
#include "FileItem.h"
#include "FolderItem.h"
#include "../EstimatePnl.h"
#include "../../CdboCompilationView.h"
#include "../../dialogs/NewCdDialog.h"


DataCompilationTreeView::DataCompilationTreeView( QWidget *parent, const char *name) :
	KListView(parent, name){

	config = new KConfig("cdbakeovenrc");
	config->setGroup("Default Settings");	
	showHidden = config->readBoolEntry("Show Hidden Items in Compilation", true);
	
	setAcceptDrops(true);
	setDropVisualizer(true);

	top = new CdboFileItem(this, "topNodeInCDBOWithStrangePath");

	
	//setItemsMovable(true);
	//setDragEnabled (true);
	//setRenameable(true);
	
	
	addColumn(  "Name"  );
    	addColumn(  "Size" );
    	addColumn(  "Modified" );
    	addColumn(  "Owner" );
    	addColumn(  "Source Location" );

    	
    	setColumnAlignment(1, AlignRight);
    	setColumnAlignment(2, AlignHCenter);
    	
    	setColumnWidth(0,210);
    	setColumnWidth(1,45);
    	setColumnWidth(2,100);
    	setColumnWidth(3,70);
    	setColumnWidth(4,220);
	
    	
	updateSettings();
	/////////////////////////////////////////////////////////////////////////
	folderMenu = new QPopupMenu();
	folderMenu -> setCheckable(true);
	
	folderMenu -> insertItem( i18n("Folder Properties"),   this ,SLOT(slotProperties()));
	
	folderMenu -> insertSeparator();
	folderMenu -> insertItem( SmallIcon("cross"), i18n("&Remove this Branch"), this ,SLOT(remove()));
	folderMenu -> insertItem( SmallIcon("reload"), i18n("Reload Directory"),   this ,SLOT(slotReload()));
	hiddenIndex = folderMenu -> insertItem( i18n("Show Hidden Items"),   this ,SLOT(slotShowHidden()));
	folderMenu->setItemChecked(hiddenIndex, showHidden);
	
	folderMenu -> insertSeparator();	
	folderMenu ->insertItem(UserIcon("isoSetup"), i18n("Modify ISO Image Properties"), this ,SLOT(compilSettingsSlot()));
	folderMenu ->insertItem(UserIcon("burn"), i18n("Create CD"), parent ,SLOT(createCD()));
	createIsoIndexInFolderMenu = folderMenu ->insertItem(UserIcon("cdImageSm"),
		i18n("Create ISO Image"), parent ,SLOT(createISO()));
	
	////////////////////////////////////////////////////////////////////////////
	fileMenu = new QPopupMenu();
	fileMenu -> setCheckable(true);
	
	fileMenu -> insertItem( i18n("File Properties"),   this ,SLOT(slotProperties()));
	fileMenu -> insertItem( i18n("Preview File With..."),
		this ,SLOT(openWithSlot()));	
	
	fileMenu -> insertSeparator();
	fileMenu->insertItem(UserIcon("cross"), i18n("&Remove this Branch"), this ,SLOT(remove()));
	fileMenu -> insertItem( BarIcon("reload"), i18n("Reload Directory"),   this ,SLOT(slotReload()));
	hiddenFIndex = fileMenu -> insertItem( i18n("Show Hidden Items"),   this ,SLOT(slotShowHidden()));
	fileMenu->setItemChecked(hiddenFIndex, showHidden);
	
	fileMenu -> insertSeparator();
	fileMenu ->insertItem(UserIcon("isoSetup"), i18n("Modify ISO Image Properties"), this ,SLOT(compilSettingsSlot()));
	fileMenu ->insertItem(UserIcon("burn"), i18n("Create CD"), parent ,SLOT(createCD()));
	createIsoIndexInFileMenu = fileMenu ->insertItem(UserIcon("cdImageSm"),
		i18n("Create ISO Image"), parent ,SLOT(createISO()));
		
	////////////////////////////////////////////////////////////////////////////
	isoMenu = new QPopupMenu();
	//isoMenu ->insertItem(UserIcon("isoSetup"), i18n("Modify ISO Image Properties"), this ,SLOT(slotProperties()));
	isoMenu ->insertItem(UserIcon("isoSetup"), i18n("Modify ISO Image Properties"), this ,SLOT(compilSettingsSlot()));
	isoMenu ->insertItem(UserIcon("burn"), i18n("Create CD"), parent ,SLOT(createCD()));
	createIsoIndex = isoMenu ->insertItem(UserIcon("cdImageSm"), i18n("Create ISO Image"), parent ,SLOT(createISO()));
	isoMenu -> insertSeparator();
	haveItemsIndex = isoMenu -> insertItem(UserIcon("cross"), i18n("Remove &All Branches"),   this ,SLOT(removeAll()));
	//////////////////////////////////////////////////////////////////////
	connect(	this, SIGNAL(returnPressed(QListViewItem *)),
						this, SLOT(slotSelectItem(QListViewItem *)));					
	connect( this, SIGNAL(rightButtonPressed(QListViewItem*, const QPoint&, int)),
					 this, SLOT(popupMenuSlot(QListViewItem*, const QPoint&, int)));
     connect(  this, SIGNAL(doubleClicked(QListViewItem *)),
						this, SLOT(slotSelectItem(QListViewItem *)));

	connect(  this, SIGNAL(dropped (QDropEvent *, QListViewItem *)),
						this, SLOT(dropOcurred(QDropEvent *, QListViewItem *)));
	
						
	//setBackgroundPixmap();
	//cerr << "backgroundPixmap()->width() " << backgroundPixmap()->width() << endl;
	//update();
	//setBackgroundMode(PaletteBackground);
	//QPixmap *pix = new QPixmap("/usr/share/apps/konqueror/tiles/punika_attack.png");
    	//setBackgroundPixmap( *pix );
		//QPixmap pix("/usr/share/apps/konqueror/tiles/kenwimer.png");
		//QPixmap pix("/usr/share/nautilus/patterns/countertop.png");
/*
    QPalette pal;
    QColorGroup cg;
    cg.setColor( QColorGroup::Foreground, black );
    cg.setColor( QColorGroup::Button, QColor( 192, 192, 192) );
    cg.setColor( QColorGroup::Light, white );
    cg.setColor( QColorGroup::Midlight, QColor( 223, 223, 223) );
    cg.setColor( QColorGroup::Dark, QColor( 96, 96, 96) );
    cg.setColor( QColorGroup::Mid, QColor( 128, 128, 128) );
    cg.setColor( QColorGroup::Text, black );
    cg.setColor( QColorGroup::BrightText, QColor( 245, 245, 245) );
    cg.setColor( QColorGroup::ButtonText, black );
    cg.setBrush( QColorGroup::Base, QBrush( white, pix ) );
    cg.setColor( QColorGroup::Background, QColor( 192, 192, 192) );
    cg.setColor( QColorGroup::Shadow, black );
    cg.setColor( QColorGroup::Highlight, QColor( 50, 40, 158) );
    cg.setColor( QColorGroup::HighlightedText, white );
    pal.setActive( cg );
    cg.setColor( QColorGroup::Foreground, black );
    cg.setColor( QColorGroup::Button, QColor( 192, 192, 192) );
    cg.setColor( QColorGroup::Light, white );
    cg.setColor( QColorGroup::Midlight, QColor( 220, 220, 220) );
    cg.setColor( QColorGroup::Dark, QColor( 96, 96, 96) );
    cg.setColor( QColorGroup::Mid, QColor( 128, 128, 128) );
    cg.setColor( QColorGroup::Text, black );
    cg.setColor( QColorGroup::BrightText, QColor( 245, 245, 245) );
    cg.setColor( QColorGroup::ButtonText, black );
    cg.setBrush( QColorGroup::Base, QBrush( white, pix ) );
    cg.setColor( QColorGroup::Background, QColor( 192, 192, 192) );
    cg.setColor( QColorGroup::Shadow, black );
    cg.setColor( QColorGroup::Highlight, QColor( 50, 40, 158) );
    cg.setColor( QColorGroup::HighlightedText, white );
    pal.setInactive( cg );
    cg.setColor( QColorGroup::Foreground, QColor( 128, 128, 128) );
    cg.setColor( QColorGroup::Button, QColor( 192, 192, 192) );
    cg.setColor( QColorGroup::Light, white );
    cg.setColor( QColorGroup::Midlight, QColor( 220, 220, 220) );
    cg.setColor( QColorGroup::Dark, QColor( 96, 96, 96) );
    cg.setColor( QColorGroup::Mid, QColor( 128, 128, 128) );
    cg.setColor( QColorGroup::Text, black );
    cg.setColor( QColorGroup::BrightText, QColor( 245, 245, 245) );
    cg.setColor( QColorGroup::ButtonText, QColor( 128, 128, 128) );
    cg.setBrush( QColorGroup::Base, QBrush( white, pix ) );
    cg.setColor( QColorGroup::Background, QColor( 192, 192, 192) );
    cg.setColor( QColorGroup::Shadow, black );
    cg.setColor( QColorGroup::Highlight, QColor( 50, 40, 158) );
    cg.setColor( QColorGroup::HighlightedText, white );
    pal.setDisabled( cg );
    setPalette( pal );
    setBackgroundOrigin( QListView::ParentOrigin );
    	
   */ 	
}
//================================================
DataCompilationTreeView::~DataCompilationTreeView(){
	delete config;
}
//====================================
void DataCompilationTreeView::setEstimate(EstimatePnl *e) {
	if(!e) return;
	estimate = e;
	connect(estimate->getRecalculateBtn(), SIGNAL(clicked ()),
						this, SLOT(recalculate()));
	connect(estimate, SIGNAL(recalculate ()),
						this, SLOT(recalculate()));
}
//==============================================================
void DataCompilationTreeView::updateSettings(){
	if(config)
 		delete config;
	config = new KConfig("cdbakeovenrc");
	config->setGroup("ISO Settings");	
	QString fn = config->readEntry("Custom ISO Name", "cdboImage_<DATE>.iso");
	config->setGroup("Default Settings");	
	if(!top)
		top = new CdboFileItem(this, "topNodeInCDBOWithStrangePath");
	top->setPixmap(0,BarIcon("cdrom_unmount", KIcon::SizeSmall ));
	top->setText(0,config->readEntry("Tmp Dir", "/tmp/") + fn);

}
//==============================================================
void DataCompilationTreeView::popupMenuSlot(QListViewItem *item, const QPoint &point, int){
	if(!item || item == top){
		setSelected(top, true);
		//setCurrentItem(top);
		if(top->childCount() == 0)
			isoMenu->setItemEnabled(haveItemsIndex, false);
		else
			isoMenu->setItemEnabled(haveItemsIndex, true);
		
		isoMenu->setItemEnabled(createIsoIndex, true);
		fileMenu->setItemEnabled(createIsoIndexInFileMenu, true);
		folderMenu->setItemEnabled(createIsoIndexInFolderMenu, true);	

		isoMenu->popup(point);
	}
	else{
		setSelected(item, true);
		if( dynamic_cast<FolderItem *>( item) ){
	  		folderMenu->setItemEnabled(createIsoIndexInFolderMenu, true);	
			folderMenu->popup( point);		
	  	}
		else{
			fileMenu->setItemEnabled(createIsoIndexInFileMenu, true);
			fileMenu->popup( point);
		}
	}
}
//====================================
//====================================
//=====  UTILITIES ====================
//====================================
//====================================
//============================================================
QString DataCompilationTreeView::currentItemPath(){
	QListViewItem *item = currentItem();
	
	if ( !item || item == top) return "";
	
	CdboFileItem *cur = dynamic_cast<CdboFileItem *> (item);
	if( cur )
		return cur->getFilePath();
	else
		return "";	
}

//============================================================
QString DataCompilationTreeView::currentItemName(){
	QListViewItem *item = currentItem();
	if ( !item || item == top) return "";
	
	CdboFileItem *cur = dynamic_cast<CdboFileItem *> (item);
	if( cur )
		return cur->getFileName();
	else
		return "";
}
//============================================================
int DataCompilationTreeView::currentItemSize(){
	QListViewItem *item = currentItem();
	if ( !item || item == top) return 0;
	
	CdboFileItem *cur = dynamic_cast<CdboFileItem *> (item);
	if( cur )
		return cur->getFileSize();	
	else
		return 0;

}
//====================================
//====================================
//=====  ACTIONS ====================
//====================================
//====================================
void DataCompilationTreeView::remove(){
	QListViewItem *item = getItemForDeletion();
	if(!item) return;
	setCurrentItem(item);

	estimate->subtract(currentItemSize() / 1024);
	fList.remove(currentItemPath());
	nameList.remove(currentItemName());
	
	top->takeItem(item);
	delete item;
	emit modified();
}
//============================================
QListViewItem* DataCompilationTreeView::getItemForDeletion(){
	QListViewItem *item = currentItem();
	if(!item || item == top) return 0;
	while(true){
		if(item->parent() == top)
			return item;
		item = item->parent();
	}
}
//===========================================================
void DataCompilationTreeView::removeAll(){
	clear();
	fList.clear();
	nameList.clear();
	top = 0;
	estimate->reset();
	updateSettings();
	emit modified();
}
//============================================
void DataCompilationTreeView::slotProperties(){
	QListViewItem *item = currentItem();
	if ( !item)
		return;
	else if(item == top)
		compilSettingsSlot();
	else{
		KPropertiesDialog *propDlg = new KPropertiesDialog( KURL( currentItemPath() ) );
		connect( propDlg, SIGNAL( applied() ), this , SLOT( slotReload() ) );
	}
}
//---------------------------------------------------------------------------------
void DataCompilationTreeView::openWithSlot(){
	QStringList list(currentItemPath());
	KFileOpenWithHandler *kfowh = new KFileOpenWithHandler();
	kfowh -> displayOpenWithDialog( KURL::List( list ) );
}

//===========================================================
void DataCompilationTreeView::collapse(){
	QListViewItem *item;
	for(item = top->firstChild(); item; item = item->nextSibling())
		item->setOpen(false);
}
//===========================================================
void DataCompilationTreeView::slotShowHidden(){
	showHidden = !folderMenu->isItemChecked(hiddenIndex);
	
	folderMenu->setItemChecked(hiddenIndex, showHidden);
	fileMenu->setItemChecked(hiddenFIndex, showHidden);
	
	QListViewItem *item;
	for(item = top->firstChild(); item; item = item->nextSibling()){
		FolderItem * i = dynamic_cast<FolderItem *>(item);
		if(i){
	  		i->setShowHidden(showHidden);
	  		i->reloadList();
			i->setOpen(false);
		}
	}
	config->setGroup("Default Settings");	
	config->writeEntry("Show Hidden Items in Compilation", showHidden);
}	
//===========================================================
void DataCompilationTreeView::slotReload(){
	QListViewItem *item = currentItem();
	if ( !item )
		return;
	if(item->parent() == top){
		FolderItem *d = dynamic_cast<FolderItem *>(item);
  		if (d)
			d->reloadList();
	}
	else{
		FolderItem *d = dynamic_cast<FolderItem *>(item->parent() );
  		if (d)
			d->reloadList();
	}
}
//---------------------------------------------------------------------------------------------
void DataCompilationTreeView::compilSettingsSlot(){
	popUpSettings(CdboCompilationView::ImageSettings);	
}
//====================================
void DataCompilationTreeView::slotSelectItem(QListViewItem * item){
	if ( !item ) return;
	
	if(item == top) {
		top->setOpen(true);
		return;
	}
	FolderItem *ftf = dynamic_cast<FolderItem *>(item);
	if (!ftf) return;
	
	emit haveStatus(i18n("Parsing directory contents. Please wait..."));
	emit processStarted();

	ftf->setOpen(!ftf->isOpen());
	
	emit processDone();
	emit haveStatus(i18n("Ready."));

}
//---------------------------------------------------------------------------------------------
void DataCompilationTreeView::keyPressEvent(QKeyEvent *e){
	if(e->key() == Key_Delete){
		remove();
	}
	if(e->key() == Key_F5){
		slotReload();
	}
}
//====================================
//====================================
//===== ADDING ITEMS ====================
//===================================
//====================================
bool DataCompilationTreeView::acceptDrag (QDropEvent* event) const{
	if(QTextDrag::canDecode(event))
		return true;
	else
		return false;
}
//====================================
void DataCompilationTreeView::dropOcurred(QDropEvent * e, QListViewItem */*item*/){
	QString path;
	if(QTextDrag::decode(e, path)){
		if(path.find("file:") != -1){
			if(addMultipleItems(path))
				e->accept();
			else
				e->ignore();
		}
		else if(addItem(path))
			e->accept();
		else
			e->ignore();
	}	
	else
		e->ignore();	
}
//================================
bool DataCompilationTreeView::addMultipleItems(QString path){
	bool valid = true;
	QString buff;
	QStringList list(QStringList::split("\n",path));
	for(int i = 0; i < (int)list.count(); i++){
		buff = list[i].replace(QRegExp("file:"), "");
		
		int p =buff.length()-1;
		if(!buff[p].isLetterOrNumber() && !buff[p].isPunct())
			buff = buff.left(p);
			
		buff.simplifyWhiteSpace();
		if(!addItem(buff)){
			valid = false;
			break;
		}
	}	
	return valid;
}
//================================
bool DataCompilationTreeView::addMultipleItems(QStringList list){
	bool valid = true;
	QString buff;
	for(int i = 0; i < (int)list.count(); i++){
		buff = list[i];
		
		int p =buff.length()-1;
		if(!buff[p].isLetterOrNumber() && !buff[p].isPunct())
			buff = buff.left(p);
			
		buff.simplifyWhiteSpace();
		if(!addItem(buff)){
			valid = false;
			break;
		}
	}	
	return valid;
}
//=========================================
bool DataCompilationTreeView::addOneItem(QString path){
	return addItem(path);
}
//=========================================
bool DataCompilationTreeView::addItem(QString path){
	if(!canAccept(path))
		return false;
	
	top->setOpen(true);
	return true;
}
//================================
bool DataCompilationTreeView::canAccept(QString path) {
	
	int size = 0;
	if(fList.contains(path) > 0){
		KMessageBox::sorry(this,
				i18n("Cannot accept: '") + path + i18n("'. "\
				"An object with the same name is already on the list!"));
		return false;
	}
	
	QFileInfo d( path );
	if(!d.exists() || !d.isReadable()){
		KMessageBox::sorry(this,
				i18n("Cannot accept '%1': "
				"Not a valid path or you do not "
				"have enough privileges to add this item.").arg(path));
		return false;
	}
	
	if(nameList.contains(d.fileName()) > 0){
		KMessageBox::sorry(this,
				i18n("Cannot accept: '") +  d.fileName() + i18n("'. "\
				"An object with the same name is already on the list!"));
		return false;
	}
	if(d.isDir()){
		FolderItem *fItem = new FolderItem( top, path, false, showHidden);
		fItem->setFileSize(0);
		nameList.append(fItem->getFileName());
		fList.append(path);
		ensureItemVisible(fItem);
		setSelected(fItem, true);
		
		//////////////////////////////////////////////
		if(map.isEmpty())
			emit processStarted();
		map.insert(path, fItem);
		calculateDirSize(path);
	}
	else{
		size = (int)d.size();
		if(!estimate->add(size / 1024)){
       		KMessageBox::sorry(this,
					i18n("Cannot accept '%1': "
					"It is too big to fit on this CD!").arg(path));
       		return false;
       	}
		addFileItem( path, size);
	}

	return true;	
}
///=========================================================
void DataCompilationTreeView::calculateDirSize( QString path){
	KIO::ListJob * listJob = KIO::listRecursive( KURL(path), false);
	listJob->setName(path.utf8());
	emit longProcessStarted(listJob);
	emit haveStatus(i18n("Calculating directory size. Please wait..."));

	connect( listJob, SIGNAL(entries( KIO::Job *, const KIO::UDSEntryList& )),
						SLOT( slotEntries( KIO::Job*, const KIO::UDSEntryList& )));
	connect(listJob, SIGNAL(result ( KIO::Job *)),
			this, SLOT(gotSize(KIO::Job *) ));
}
///=========================================================
void DataCompilationTreeView::slotEntries( KIO::Job* job, const KIO::UDSEntryList & list ){
	KIO::UDSEntryListConstIterator it = list.begin();
	KIO::UDSEntryListConstIterator end = list.end();
	bool checked = false, noGood = false;
	bool dir = false;
	long size = 0;
	QString id = job->name();
	FolderItem *folderItem = map[id];

	for (; it != end; ++it) {
		KIO::UDSEntry::ConstIterator it2 = (*it).begin();
		for( ; it2 != (*it).end(); it2++ ) {
			switch( (*it2).m_uds ) {
			
              		case KIO::UDS_LINK_DEST:{///FIXME:: handle links
             				noGood = true;
             				break;
              		}
              		case KIO::UDS_FILE_TYPE:{
              			if((*it2).m_long == 16384){
              				dir = true;
              			}
              			else{
              				dir = false;
             			}
              			break;
              		}
              		case KIO::UDS_NAME:{
             				if((*it2).m_str == "." || (*it2).m_str == ".."){
             					noGood = true;
             					break;
             				}
					break;
              		}
              		case KIO::UDS_SIZE:{
              			if(!dir){
              				size = (*it2).m_long;
					}
					break;
              		}
              		default:
					break;
			}
			if(noGood)
				break;
		}
		if(!noGood && !dir){
			size = folderItem->getFileSize() + size;
			if(!estimate->canAdd(size / 1024)){
				if(job){	
					job->kill();
				//delete job;
				}
				KMessageBox::sorry(this,
					i18n("Cannot accept '%1': "
					"It is too big to fit on this CD!").arg(id));
				emit longProcessDone(job);
				longProcessCanceled(id);
				return;
			}
			folderItem->setFileSize(size);
		}
		noGood = false;
	}
}
//====================================
void DataCompilationTreeView::gotSize(KIO::Job *job){
	if ( job->error() )
		return;
	emit longProcessDone(job);
	FolderItem *folderItem = map[job->name()];
	if(!estimate->add(folderItem->getFileSize() / 1024)){
		KMessageBox::sorry(this,
					i18n("Cannot accept '%1': "
					"It is too big to fit on this CD!").arg(job->name()));
		longProcessCanceled(job->name());
		return;
	}
	map.remove(job->name());
	
	if(map.isEmpty()){
		emit modified();
		emit processDone();
		emit haveStatus(i18n("Ready."));
	}
}
//========================
void DataCompilationTreeView::longProcessCanceled(QString id){

	FolderItem *cur = map[id];
	setCurrentItem(cur);
	cur->setFileSize(0);
	remove();
	
	map.remove(id);
	if(map.isEmpty()){		
		emit processDone();
		emit haveStatus(i18n("Ready."));
	}
}
//==============================================================
void DataCompilationTreeView::addFileItem(QString path, int size){
	FileItem *fItem = new FileItem( top, path);
	fItem->setFileSize(size);
	
	nameList.append(fItem->getFileName());
	
	fList.append(path);
	ensureItemVisible(fItem);
	setSelected(fItem, true);
	emit modified();
}
//==============================================================
void DataCompilationTreeView::recalculate(){
	estimate->reset();
	emit haveStatus(i18n("Recalculating image size. Please wait..."));
     		
	QListViewItem *item;
	FileItem *fileItem;
	FolderItem *folderItem;
	
	for(item = top->firstChild(); item; item = item->nextSibling()){
		
		fileItem = dynamic_cast<FileItem *>(item);
		if(fileItem){
			QFileInfo d( fileItem->getFilePath() );
			
			if(!d.exists() || !d.isReadable()){
              		KMessageBox::sorry(this,
              				i18n("Cannot accept: '") +  fileItem->getFilePath() + i18n("'. "\
              				"This path is no longer valid! or possibly you do not "\
              				"have enough privileges to use this item."));
              		setCurrentItem(fileItem);
				remove();
				continue;
              	}
              	int size = (int)d.size();
              	
              	if(!estimate->add(size / 1024)){
       			KMessageBox::sorry(this,
					i18n("Cannot accept '%1': "
					"It is too big to fit on this CD!").arg( fileItem->getFilePath()));
       			setCurrentItem(fileItem);
				remove();
				continue;
       		}
			
			fileItem->setFileSize(size);
		
		}
		else if((folderItem = dynamic_cast<FolderItem *>(item)) != NULL){
			
			QFileInfo d( folderItem->getFilePath() );
			
			if(!d.exists() || !d.isReadable()){
              		KMessageBox::sorry(this,
              				i18n("Cannot accept: '") +  fileItem->getFilePath() + i18n("'. "\
              				"This path is no longer valid! or possibly you do not "\
              				"have enough privileges to use this item."));
              		setCurrentItem(folderItem);
				remove();
				continue;
              	}
      		//////////////////////////////////////////////
			folderItem->setFileSize(0);
			if(map.isEmpty())
				emit processStarted();
			map.insert(folderItem->getFilePath(), folderItem);
			calculateDirSize(folderItem->getFilePath());
		}
		else
			continue;
	}
	if(map.isEmpty()){		
		emit processDone();
		emit haveStatus(i18n("Ready."));
	}
}

