
/***************************************************************************
                          ApollonSharedViewTab.h  -  description
                             -------------------
begin		: June 05 2003
copyright	: (C) 2003 Martin Koebele
email		: apollon@mkoebele.de
description	:

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 <assert.h>
#include <iostream>
using namespace std;
#include <cstdlib>

#include <dcopclient.h>
#include <kapplication.h>
#include <kdirselectdialog.h>
#include <kfiletreeview.h>
#include <kiconloader.h>
#include <kimagefilepreview.h>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpopupmenu.h>
#include <kprocess.h>
#include <kurl.h>

#include <qcstring.h>
#include <qdir.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlistview.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qsizepolicy.h>
#include <qsplitter.h>
#include <qstring.h>
#include <qcstring.h>
#include <qdatastream.h>
#include <qvbox.h>

#include "apollonplayertab.h"
#include "apollonsharedviewtab.h"


ApollonSharedViewTab::ApollonSharedViewTab(QWidget *parent, const QString &/*name*/) :
  ApollonTab(parent),
  m_playerTab(0)
{
	KIconLoader *loader = KGlobal::iconLoader();

	QSplitter *splitter = new QSplitter(this);
	splitter->setOrientation(QSplitter::Horizontal);

	QVBox *box = new QVBox(splitter);
	box->setMaximumWidth(350);

	m_listView = new KFileTreeView(box);
	m_listView->setSelectionMode(QListView::Extended);
	m_listView->addColumn(i18n("Folders"));
	m_listView->setAllColumnsShowFocus(true);
	m_listView->setRootIsDecorated(true);
	m_listView->setShowSortIndicator(true);
	m_listView->setItemsMovable(true);
	m_listView->setSorting(0, true);

	m_syncButton = new QPushButton(loader->loadIcon("reload", KIcon::Small), "&Synchronize", box);

	m_kpv = new KImageFilePreview(splitter);

	splitter->show();

	connect(m_listView, SIGNAL(doubleClicked(QListViewItem *,const QPoint &, int)),       this, SLOT(doubleClicked(QListViewItem *, const QPoint &, int) ));
	connect(m_listView, SIGNAL(rightButtonPressed(QListViewItem *, const QPoint &, int)), this, SLOT(popUp(QListViewItem *, const QPoint &, int)));
	connect(m_listView, SIGNAL(itemRenamed(QListViewItem *, int)),                        this, SLOT(rename(QListViewItem *, int)));
	connect(m_listView, SIGNAL(currentChanged(QListViewItem *)),                          this, SLOT(preview(QListViewItem *)));
	connect(m_syncButton, SIGNAL(clicked()),                                              this, SIGNAL(syncShares()));

	m_popupMenu = new KPopupMenu(m_listView);
	m_popupMenu->insertItem(loader->loadIcon("player_play", KIcon::Small), i18n("&Play"),                 this, SLOT(playFile()),      Key_Return, 0);
	m_popupMenu->insertSeparator();
	m_popupMenu->insertItem(loader->loadIcon("xmms",        KIcon::Small), i18n("Add to &XMMS playlist"), this, SLOT(addFileToXMMS()), Key_X,      1);
	m_popupMenu->insertItem(loader->loadIcon("juk",         KIcon::Small), i18n("Add to &JuK playlist"),  this, SLOT(addFileToJuK()),  Key_J,      2);
	m_popupMenu->insertItem(loader->loadIcon("amarok", KIcon::Small), i18n("Add to &amarok playlist"), this, SLOT(addFileToAmarok()), Key_A, 3);
	m_popupMenu->insertSeparator();
	m_popupMenu->insertItem(loader->loadIcon("editdelete",  KIcon::Small), i18n("&Delete file"),          this, SLOT(deleteFile()),    Key_Delete, 4);
	m_popupMenu->insertItem(                                               i18n("&Rename file"),          this, SLOT(renameFile()),    Key_F2,     5);
	//m_popupMenu->setItemEnabled(4, true);

	m_id = 0;
	m_moveToMenu = new KPopupMenu(m_listView);
	m_moveToMenu->insertItem(i18n("Browse..."), m_id++);
	m_moveToMenu->insertSeparator();
	m_popupMenu->insertItem(i18n("Move to: ..."), m_moveToMenu);

	connect(m_moveToMenu, SIGNAL(activated(int)), this, SLOT(moveTo(int)));
}

ApollonSharedViewTab::~ApollonSharedViewTab()
{
}

void ApollonSharedViewTab::addFolder(const QString &folder)
{
	QString path = folder;
	if(path != "none")
	{
		QString home(getenv("HOME"));
		path = path.replace(QString("~"), home);

		KFileTreeBranch *branch = m_listView->addBranch(KURL(path), path);
		branch->root();
		KIconLoader *loader = KGlobal::iconLoader();
		m_moveToMenu->insertItem(loader->loadIcon("folder", KIcon::Small), path, m_id++);
  	}
}

void ApollonSharedViewTab::doubleClicked(QListViewItem *item, const QPoint &/*point*/, int /*col*/)
{
	play((KFileTreeViewItem *) item);
}

void ApollonSharedViewTab::popUp(QListViewItem */*item*/, const QPoint &point, int /*col*/)
{
	m_popupMenu->popup(point);
}

void ApollonSharedViewTab::playFile()
{
	m_currentItem = (KFileTreeViewItem *) m_listView->currentItem();

	if(m_currentItem->isDir())
		KMessageBox::sorry(this, i18n("Sorry, I can't play directories."), i18n("Sorry"));
	else
		play(m_currentItem);
}

void ApollonSharedViewTab::addFileToXMMS()
{
	m_currentItem = (KFileTreeViewItem *) m_listView->firstChild();
	m_currentItem = (KFileTreeViewItem *) m_currentItem->firstChild();
	while(m_currentItem != 0)
	{
		if(m_currentItem->isSelected())
		{
			KProcess xmmsCommand;
			xmmsCommand << "xmms" << "--enqueue" << m_currentItem->url().path();
			xmmsCommand.start(KProcess::DontCare);
		}
		m_currentItem = (KFileTreeViewItem *) m_currentItem->nextSibling();
	}
}

void ApollonSharedViewTab::addFileToJuK()
{
	if (isRunning("juk"))
	{
		m_currentItem = (KFileTreeViewItem *) m_listView->firstChild();
		m_currentItem = (KFileTreeViewItem *) m_currentItem->firstChild();
		while (m_currentItem != 0)
		{
			if (m_currentItem->isSelected())
			{
				QString file_url = m_currentItem->url().path();

				if(!kapp->dcopClient()->send("juk", "Collection", "openFile(QString)", file_url))
				{
					KMessageBox::sorry(this, i18n("I couldn't contact JuK."), i18n("Sorry"));
				}
			}
			m_currentItem = (KFileTreeViewItem *) m_currentItem->nextSibling();
		}
	}
}

void ApollonSharedViewTab::addFileToAmarok()
{
	if (isRunning("amarok"))
	{
		m_currentItem = (KFileTreeViewItem *) m_listView->firstChild();
		m_currentItem = (KFileTreeViewItem *) m_currentItem->firstChild();
		while (m_currentItem != 0)
		{
			if (m_currentItem->isSelected())
			{
				KURL file_url = m_currentItem->url();
				QByteArray data;
				QDataStream arg(data, IO_WriteOnly);
				arg << file_url;
				if(!kapp->dcopClient()->send("amarok", "player", "addMedia(KURL)", data))
				{
					KMessageBox::sorry(this, i18n("I couldn't contact amarok."), i18n("Sorry"));
				}
			}
			m_currentItem = (KFileTreeViewItem *) m_currentItem->nextSibling();
		}
	}
}


void ApollonSharedViewTab::play(KFileTreeViewItem *item)
{
	assert(m_playerTab != 0);

	m_playerTab->play(item->url());
}

void ApollonSharedViewTab::deleteFile()
{
	QDir dir;
	m_currentItem = (KFileTreeViewItem *) m_listView->firstChild();
	m_currentItem = (KFileTreeViewItem *) m_currentItem->firstChild();
	while(m_currentItem != 0)
	{
		if(m_currentItem->isSelected())
		{
			if(!m_currentItem->isDir())
			{
				int answer = KMessageBox::warningYesNo(this, i18n("Do you want to delete %1?").arg(m_currentItem->path()), i18n("Deletion"));
				if(answer == KMessageBox::Yes)
				{
					dir.remove(m_currentItem->path());
				}
			}
			else
			{
				KMessageBox::sorry(this, i18n("Deleting an entire directory?\n (has no effect)"), i18n("Sorry"));
			}
		}
		m_currentItem = (KFileTreeViewItem *) m_currentItem->nextSibling();
	}
}

void ApollonSharedViewTab::renameFile()
{
	m_popupMenu->setAccel(0, 0);
	m_currentItem = m_listView->currentKFileTreeViewItem();
	m_currentItem->setRenameEnabled(0, true);

	if(m_currentItem->renameEnabled(0))
	{
		m_currentItem->startRename(0);
	}
	else
	{
		KMessageBox::sorry(this, i18n("Couldn't rename file or directory"), i18n("Sorry"));
	}
}

void ApollonSharedViewTab::rename(QListViewItem *item, int col)
{
	QString newName = item->text(col);
	KURL url = m_currentItem->path();
	QString newFileName = url.directory() + QString("/") + newName;
	QDir dir;
	if(!dir.rename(m_currentItem->path(), newFileName))
	{
		KMessageBox::error(this, i18n("Couldn't rename file or directory!"), i18n("Sorry"));
	}
	m_popupMenu->setAccel(Key_Return, 0);
}

void ApollonSharedViewTab::moveTo(int id)
{
	m_listView->setSelectionMode(QListView::Single);
	m_currentItem = m_listView->currentKFileTreeViewItem();
	m_currentItem->text(0);
	cout << "#################" << endl;
	if(id == 0) // browse
	{
		KURL newUrl = KDirSelectDialog::selectDirectory();

		if(!newUrl.isEmpty())
		{
			KURL url = m_currentItem->path();
			QString filename = url.fileName();
			QDir dir;
			QString newPath = newUrl.path() + QString("/") + filename;
			QString oldPath = url.path();
			if(!dir.rename(oldPath, newPath))
			{
				KMessageBox::error(this, i18n("Couldn't move file or directory!"), i18n("Error"));
			}
		}
	}
	else
	{
		m_currentItem = m_listView->currentKFileTreeViewItem();
		KURL url = m_currentItem->path();
		QString filename = url.fileName();
		QDir dir;
		QString newPath = m_moveToMenu->text(id) + QString("/") + filename;
		QString oldPath = url.path();
		if(!dir.rename(oldPath, newPath))
		{
			KMessageBox::error(this, i18n("Couldn't move file or directory!"), i18n("Error"));
		}
	}
	m_listView->setSelectionMode(QListView::Extended);
}

void ApollonSharedViewTab::preview(QListViewItem *item)
{
	m_currentItem = (KFileTreeViewItem *) item;
	KURL url = m_currentItem->path();
	m_kpv->showPreview(url);
}

bool ApollonSharedViewTab::isRunning(QString app)
{
	QCStringList allApps = kapp->dcopClient()->registeredApplications();
	QValueList<QCString>::iterator iterator;
	QByteArray data, replyData;
	QCString replyType;
	bool found = false;

	for (iterator = allApps.begin(); iterator != allApps.end(); iterator++)
	{
		if ((*iterator).contains(app,false))
		{
			found = true;
		}
	}

	if (!found)
	{
		int answer = KMessageBox::warningYesNo(this, i18n("%1 is not running!\n If %1 is properly installed, Apollon could try to start it.\n"
		                                                  "Shall Apollon try to start %1?\n\n"
		                                                  "Note: the file won't be added, try it again after the program is loaded.").arg(app),
		                                             i18n("%1 is not running").arg(app));
		if (answer == KMessageBox::Yes)
		{
			KProcess appCommand;
			appCommand << app;
			appCommand.start(KProcess::DontCare);
			found = true;
		}
	}
	return found;
}

#include "apollonsharedviewtab.moc"

