/***************************************************************************
                          FilesListView.cpp  -  description
                             -------------------
    begin                : Sat Jul 14 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>
// QT includes
#include <qdir.h>
#include <qstringlist.h>
#include <qpopupmenu.h>
#include <qclipboard.h>
#include <qapp.h>
#include <qfileinfo.h>
#include <qheader.h>
#include <qdragobject.h>
#include <qcheckbox.h>


// KDE includes
#include <kurl.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kio/job.h>
#include <kpropsdlg.h>
#include <kopenwith.h>
#include <kio/netaccess.h>
#include <kmessagebox.h>
#include <kmimetype.h>
#include <kcombobox.h>
#include <kconfig.h>
#include <kapplication.h>

// CDBO includes
#include "FilesListView.h"
#include "FilesListView.moc"
#include "FileItem.h"
#include "FolderItem.h"
#include "../SrcListCntPanel.h"


FilesListView::FilesListView( QWidget *parent, const char *name, QString dir) : KListView(parent, name){
	
	addColumn(  "Name"  );
    	addColumn(  "Size" );
    	addColumn(  "Modified" );
    	//addColumn(  "Permissions" );
    	addColumn(  "Owner" );
	
    	setColumnAlignment(1, AlignRight);
    	setColumnAlignment(2, AlignHCenter);
    	
    	setColumnWidth(0,180);
    	setColumnWidth(1,45);
    	setColumnWidth(2,100);
    	setColumnWidth(3,70);
    	
	setDragEnabled(true);
	//setSelectionModeExt(Konqueror);
	setSelectionMode(QListView::Extended);

	
	////////////////////////////////////////////////////////////////////////////////////////
    	config = kapp->config();
	config->setGroup("Default Settings");	
	showHidden = config->readBoolEntry("Show Hidden Files On List", true);
	showFolders = config->readBoolEntry("Show Folders On Files List", false);
	nameFilter = "";
	
	popupMenu = new QPopupMenu();
	
	addIndex = popupMenu -> insertItem(BarIcon("bottom"),  i18n("&Add to Compilation List"),
			this ,SLOT(slotAddToCompilation()));
	popupMenu -> insertSeparator();
	
	propIndex = popupMenu -> insertItem( i18n("Properties..."),   this ,SLOT(filePropertiesSlot()));
	
	prevIndex = popupMenu -> insertItem( i18n("Preview With..."),
		this ,SLOT(openWithSlot()));	
	
	popupMenu -> insertSeparator();
	showFoldersIndex = popupMenu -> insertItem( i18n("Show Directories"),   this ,SLOT(slotShowFolders()));
	popupMenu->setItemChecked(showFoldersIndex, showFolders);
	showHiddenIndex = popupMenu -> insertItem( i18n("Show Hidden"),   this ,SLOT(slotShowHidden()));
	popupMenu->setItemChecked(showHiddenIndex, showHidden);
	popupMenu -> insertSeparator();
	popupMenu -> insertItem( BarIcon("reload"), i18n("Reload File List"),   this ,SLOT(reloadListSlot()));
	
	connect( this, SIGNAL(rightButtonPressed(QListViewItem*, const QPoint&, int)),
					 this, SLOT(popupMenuSlot(QListViewItem*, const QPoint&, int)));
	connect(  this, SIGNAL(doubleClicked(QListViewItem *)),
						this, SLOT(slotSelectFile(QListViewItem *)));

	connect(	this, SIGNAL(returnPressed(QListViewItem *)),
						this, SLOT(slotSelectFile(QListViewItem *)));

	this->parent = 0;
	/*if(parent)
		cerr << parent->text(0);*/
}
FilesListView::~FilesListView(){
}
//---------------------------------------------------------------------------------
/*void FilesListView::loadDir( QString path  ){
	if(!path) return;
	clear();
	
	dirPath = path;
	//cerr << "reading: " << path << endl;
	QDir dir(path);
	
	if(showHidden){
		if(!showFolders)
			dir.setFilter( QDir::Files|QDir::Hidden);
		else
			dir.setFilter( QDir::Dirs|QDir::Files|QDir::Hidden);
	}
	else{
		if(!showFolders)
			dir.setFilter( QDir::Files);
		else
			dir.setFilter( QDir::Dirs|QDir::Files);
	}
	
	dir.setSorting( QDir::Name);
	
	
	if(nameFilter != "")
		dir.setNameFilter(nameFilter);
	
	QStringList dirList = dir.entryList();
			
	FileItem *fItem;
	for ( int i = 0; i < (int)dirList.count(); ++i )
		fItem = new FileItem( this, path + "/" + dirList[i]);
				
}*/
//---------------------------------------------------------------------------------
void FilesListView::loadDir( FolderItem *p  ){
	if(!p) return;
	parent = p;
	
	QString path = parent->getFilePath();
	clear();
	dirPath = path;
	//cerr << "reading: " << path << endl;
	QDir dir(path);
	dir.setSorting( QDir::Name);	
	if(nameFilter != "")
		dir.setNameFilter(nameFilter);
		
	QStringList dirList;
	
//////////////////// adding folders //////////////////////////////////////////////////////
	if(showFolders){
		if(showHidden)
			dir.setFilter (QDir::Hidden|QDir::Dirs);
		else
			dir.setFilter ( QDir::Dirs);
		
		dirList = dir.entryList();
		dirList.remove(".");
		dirList.remove("..");
		
		FolderItem *dItem;
		for ( int i = 0; i < (int)dirList.count(); ++i )
			dItem = new FolderItem( this, path + "/" + dirList[i], false, showHidden);
	}
//////////////////// adding files //////////////////////////////////////////////////////
		
	if(showHidden)
		dir.setFilter (QDir::Hidden|QDir::Files);
	else
		dir.setFilter ( QDir::Files);

	dirList = dir.entryList();
	FileItem *fItem;
	for ( int i = 0; i < (int)dirList.count(); ++i )
		fItem = new FileItem( this, path + "/" + dirList[i]);
}
//---------------------------------------------------------------------------------
void FilesListView::reloadListSlot(){
	if(!parent)
		return;
	if(cnt){
		nameFilter = cnt->getFilterByCmb()->currentText();
		if(nameFilter != "" && !cnt->getFilterByCmb()->contains(nameFilter))
			cnt->getFilterByCmb()->insertItem(nameFilter);
		loadDir(parent);
	}
}
//---------------------------------------------------------------------------------
void FilesListView::checkShowHidden(){
	if(cnt){
		showHidden = cnt->getShowHiddenChk()->isChecked();
		popupMenu->setItemChecked(showHiddenIndex, showHidden);
		reloadListSlot();
		////////////////////////////////////////////////////////////////////////////////////////
    		config->setGroup("Default Settings");	
		config->writeEntry("Show Hidden Files On List", showHidden);
	}
}
//---------------------------------------------------------------------------------
void FilesListView::slotShowHidden(){
	showHidden = !popupMenu->isItemChecked(showHiddenIndex);
	if(cnt)
		cnt->getShowHiddenChk()->setChecked(showHidden);
	popupMenu->setItemChecked(showHiddenIndex, showHidden);
	
	config->setGroup("Default Settings");	
	config->writeEntry("Show Hidden Files On List", showHidden);
	reloadListSlot();
}
//---------------------------------------------------------------------------------
void FilesListView::slotShowFolders(){
	showFolders = !popupMenu->isItemChecked(showFoldersIndex);
	
	popupMenu->setItemChecked(showFoldersIndex, showFolders);
	
	//loadDir(dirPath);
	////////////////////////////////////////////////////////////////////////////////////////
    	config->setGroup("Default Settings");	
	config->writeEntry("Show Folders On Files List", showFolders);
	reloadListSlot();
}

//---------------------------------------------------------------------------------
void FilesListView::slotAddToCompilation(){
	if ( !currentItem() ) return;
	QString sp = "";
	
	QList<QListViewItem> list = selectedItems();
	for(CdboFileItem *item = (CdboFileItem *)list.first(); item; item = (CdboFileItem *)list.next()){
		sp = sp + "\nfile:" + item->getFilePath() ;
	}
	
	emit addToCompilation( sp );
}
//=============================================
QDragObject *FilesListView::dragObject(){
	if ( !currentItem() ) return 0;
	
	QString sp = "";
	
	QList<QListViewItem> list = selectedItems();
	for(CdboFileItem *item = (CdboFileItem *)list.first(); item; item = (CdboFileItem *)list.next()){
		sp = sp + "\nfile:" + item->getFilePath() ;
	}

	QDragObject *d = new QTextDrag(sp, (QWidget *)this);
	const QPixmap *p = currentItem()->pixmap(0);
	d->setPixmap(*p);
	return d;
}

//---------------------------------------------------------------------------------
void FilesListView::openWithSlot(){
	if ( !currentItem() ) return;
	
	CdboFileItem *fItem = dynamic_cast<CdboFileItem *>(currentItem());
  	if (!fItem) return;
  	
	QString sp = fItem->getFilePath();
	
	QStringList list;
	list.append(sp);
	
	KFileOpenWithHandler *kfowh = new KFileOpenWithHandler();
	
	kfowh -> displayOpenWithDialog( KURL::List( list ) );
}
//---------------------------------------------------------------------------------
void FilesListView::filePropertiesSlot(){
	if(!currentItem()) return;

	CdboFileItem *fItem = dynamic_cast<CdboFileItem *>(currentItem());
  	if (!fItem) return;
  	
	QString sp = fItem->getFilePath();

  	KPropertiesDialog *propDlg = new KPropertiesDialog( KURL(sp ) );
  	connect( propDlg, SIGNAL( applied() ), this , SLOT( reloadListSlot() ) );
}
//---------------------------------------------------------------------------------
void FilesListView::popupMenuSlot(QListViewItem* item, const QPoint& point, int){
	if (item ){
		setSelected(item, true);
		popupMenu->setItemEnabled(addIndex, true);
		popupMenu->setItemEnabled(prevIndex, true);
		popupMenu->setItemEnabled(propIndex, true);

	}
	else{
		popupMenu->setItemEnabled(addIndex, false);
		popupMenu->setItemEnabled(prevIndex, false);
		popupMenu->setItemEnabled(propIndex, false);
	}

	popupMenu->popup(point);
	
}
//---------------------------------------------------------------------------------------------
void FilesListView::keyPressEvent(QKeyEvent *e){
	if(e->key() == Key_F5){
		reloadListSlot();
	}
	if(e->key() == Key_Left || e->key() == Key_Right || e->key() == Key_Plus || e->key() == Key_Minus){
		return;
	}
	KListView::keyPressEvent(e);
}
//---------------------------------------------------------------------------------
void FilesListView::slotSelectFile(QListViewItem * item){
	FolderItem *folderItem = dynamic_cast<FolderItem *>(item);
	if(!folderItem)
		return;
	else{
		parent->setOpen(true);
		for(FolderItem *i = (FolderItem *)parent->firstChild(); i; i=(FolderItem *)i->nextSibling()){
			if(folderItem->getFileName() == i->getFileName()){
				parent->listView()->ensureItemVisible(i);
				emit folderClicked(i);
				return;
			}
		}
	}
}
