/***************************************************************************
                          PreviewDialog.cpp  -  description
                             -------------------
    begin                : Fri Jun 1 2001
    copyright            : (C) 2001 by Alex 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 <qapp.h>
#include <qframe.h>
#include <qheader.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <qvariant.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qpopupmenu.h>

#include <klistview.h>
#include <kpropsdlg.h>
#include <kopenwith.h>
#include <kio/netaccess.h>
#include <kio/job.h>
#include <klocale.h>
#include <kconfig.h>
#include <kurl.h>

#include <kprocess.h>

#include "PreviewDialog.h"
#include "PreviewDialog.moc"
#include "../widgets/fileViews/FileItem.h"
#include "../widgets/fileViews/FolderItem.h"


PreviewDialog::PreviewDialog( QWidget* parent,  const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl ){
	if ( !name )
       	setName( "PreviewDialog" );
	resize( 301, 421 );


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

       layout = new QVBoxLayout( this );
       layout->setSpacing( 6 );
       layout->setMargin( 11 );

       filesView = new KListView( this, "filesView" );
       filesView->setRootIsDecorated( true );
	filesView->header()->hide();
	
       filesView->setLineWidth( 2 );
       filesView->addColumn( i18n( "Name" ) );
       layout->addWidget( filesView );

       line = new QFrame( this, "line" );
       line->setFrameStyle( QFrame::HLine | QFrame::Sunken );
       layout->addWidget( line );

       closeBtn = new QPushButton( this, "closeBtn" );
       closeBtn->setText( i18n( "&Close" ) );
       QToolTip::add(  closeBtn, i18n( "Close this dialog." ) );
       layout->addWidget( closeBtn );
	
	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();
	hiddenFIndex = fileMenu -> insertItem( i18n("Show Hidden Items"),   this ,SLOT(slotShowHidden()));
	fileMenu->setItemChecked(hiddenFIndex, showHidden);
	//fileMenu -> insertItem( BarIcon("reload"), i18n("Reload Directory"),   this ,SLOT(slotReload()));


	connect( filesView, SIGNAL(returnPressed(QListViewItem *)),
						this, SLOT(slotSelectItem(QListViewItem *)));					
	connect( filesView, SIGNAL(rightButtonPressed(QListViewItem*, const QPoint&, int)),
					 this, SLOT(popupMenuSlot(QListViewItem*, const QPoint&, int)));
     connect(  filesView, SIGNAL(doubleClicked(QListViewItem *)),
						this, SLOT(slotSelectItem(QListViewItem *)));
						
       connect( closeBtn, SIGNAL( clicked() ), this, SLOT( quitSlot() ) );
}
//===================================================
PreviewDialog::~PreviewDialog(){
	delete config;
}
/*//----------------------------------------------------------------------------------------------
bool PreviewDialog::open(QString location, bool image){
	
	cerr << "Openning: " << location << endl;
	
	setCaption( i18n(location) );
	
	mountPoint = KIO::findDeviceMountPoint(location);
	if(mountPoint && mountPoint != ""){
		umount = false;
		top = new FolderItem(filesView, mountPoint, false, showHidden);
		top->setText(0,location);	
		//return true;
	}
	else{
		umount = true;
		config->setGroup("Default Settings");		
		QString buff = config->readEntry("Tmp Dir", "/tmp/")  + "cdPreview";
		KIO::NetAccess::mkdir(KURL(buff));
		mountPoint = buff ;
		if(image){
		
		;
		}
		else{
			KIO::mount(true, "iso9660", location, mountPoint);
			top = new FolderItem(filesView, buff, false, showHidden);
			top->setText(0,location);
		}
		
	}
	return true;
}*/
//----------------------------------------------------------------------------------------------
bool PreviewDialog::open(QString location, bool image){
	
	QString buff;
	setCaption( location );
	
	mountPoint = KIO::findDeviceMountPoint(location);
	if(!mountPoint.isEmpty()){
		umount = false;
		top = new FolderItem(filesView, mountPoint, false, showHidden);
		top->setText(0,location);	
		remTDir = false;
		return true;
	}
	else{
		umount = true;
		config->setGroup("Default Settings");		
		buff = config->readEntry("Tmp Dir", "/tmp/")  + ".preview";
		if(!KIO::NetAccess::mkdir(KURL(buff)))
			remTDir = false;
		else
			remTDir = true;
			
		mountPoint = buff ;
		
		cdboProc = new KShellProcess();
		*cdboProc << " mount -t iso9660 ";
			
		if(image)
			*cdboProc << " -o ro,loop=/dev/loop0 ";
		
		*cdboProc << "\"" + location + "\"";
		*cdboProc << "\"" + mountPoint + "\"";
		
				
		QApplication::connect(cdboProc, SIGNAL(processExited(KProcess *)),
     					this, SLOT(mounted(KProcess *)));
	
		if(!cdboProc->start(KProcess::NotifyOnExit)){
			delete cdboProc;
			if(remTDir)
				KIO::NetAccess::del(mountPoint);
			return false;
		}
	}
	top = new FolderItem(filesView, buff, false, showHidden);
	top->setText(0,location);
	return true;
}
//==============================================================
void PreviewDialog::popupMenuSlot(QListViewItem *item, const QPoint &point, int){
	if(!item) return;
	filesView->setSelected(item, true);
	fileMenu->popup( point);
}
//===========================================================
void PreviewDialog::slotShowHidden(){
	showHidden = !fileMenu->isItemChecked(hiddenFIndex);
	
	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 PreviewDialog", showHidden);
}	
//============================================
void PreviewDialog::slotProperties(){
	/*QListViewItem *item = filesView->currentItem();
	if ( !item)
		return;
  	else{
  		KPropertiesDialog *propDlg = new KPropertiesDialog( KURL( currentItemPath() ) );
  		//connect( propDlg, SIGNAL( applied() ), this , SLOT( slotReload() ) );
  	}*/
}
//---------------------------------------------------------------------------------
void PreviewDialog::openWithSlot(){
	QStringList list(currentItemPath());
	KFileOpenWithHandler *kfowh = new KFileOpenWithHandler();
	kfowh -> displayOpenWithDialog( KURL::List( list ) );
}
//====================================
void PreviewDialog::slotSelectItem(QListViewItem * item){
	if ( !item ) return;
	
	FolderItem *ftf = dynamic_cast<FolderItem *>(item);
	if (!ftf) return;

	ftf->setOpen(!ftf->isOpen());
}
//============================================================
QString PreviewDialog::currentItemPath(){
	QListViewItem *item = filesView->currentItem();
	if ( !item) return "";///????????????????????????????????
	//(item == top)
	FolderItem *cur = dynamic_cast<FolderItem *> (item);
	if( cur )
		return cur->getFilePath();
	else{
		FileItem *i = dynamic_cast<FileItem *> (item);
		return i->getFilePath();	
	}
}

//---------------------------------------------------------------------------------------------
void PreviewDialog::mounted(KProcess *proc){
	delete proc;	
}	
//============================================================
void PreviewDialog::quitSlot(){
	if(!umount) {//KIO::unmount(mountPoint);
		if(remTDir)
			KIO::NetAccess::del(mountPoint);	
		accept();
	}
		
	cdboProc = new KShellProcess();
	*cdboProc << "umount ";
	*cdboProc << "\"" + mountPoint + "\"";
	QApplication::connect(cdboProc, SIGNAL(processExited(KProcess *)),
     		this, SLOT(unMounted(KProcess *)));
	
	if(!cdboProc->start(KProcess::NotifyOnExit)){
		delete cdboProc;
		accept();
	}
}
//---------------------------------------------------------------------------------------------
void PreviewDialog::keyPressEvent(QKeyEvent *e){
	if(e->key() == Key_Escape){
        	quitSlot();
	}
}
//---------------------------------------------------------------------------------------------
void PreviewDialog::closeEvent(QCloseEvent *e){
	e->ignore();
	quitSlot();
}
//---------------------------------------------------------------------------------------------
void PreviewDialog::unMounted(KProcess *proc){
	delete proc;
	if(remTDir)
		KIO::NetAccess::del(mountPoint);
	accept();	
}
