#include "Uploads.moc"
#include "EditUpload.h"
#include <qlabel.h>
#include <qlistbox.h>
#include <qpushbutton.h>
#include <kapplication.h>
#include <klocale.h>

// getqlbsel: Return number of selected item in a QListBox
int getqlbsel(QListBox const * const lb)
{
	for(unsigned int i=0;i<lb->count();i++)
		if(lb->isSelected(i))
			return i;
	return -1;
}

Uploads::Uploads(QWidget *parent, const char *name)
 : UploadsBase(parent,name)
{
	connect(addUpload,SIGNAL(clicked()),SLOT(addUploadPressed()));
	connect(editUpload,SIGNAL(clicked()),SLOT(editUploadPressed()));
	connect(rmUpload,SIGNAL(clicked()),SLOT(rmUploadPressed()));
}
Uploads::~Uploads()
{
}
void Uploads::ftpaccessLoaded(ftpaccess *xs)
{
	ftpxs=xs;
	redraw();
}
void Uploads::update()
{
	redraw();
}
void Uploads::addUploadPressed()
{
	EditUpload e(0);
	connect(&e,SIGNAL(EditUploadDone(ftpupload *)),this,SLOT(UploadAdded(ftpupload *)));
	e.exec();
}
void Uploads::editUploadPressed()
{
	int item=getqlbsel(uploads);
	if(item!=-1) {
		EditUpload e(ftpxs->getUploadNo(item));
		connect(&e,SIGNAL(EditUploadDone(ftpupload *)),this,SLOT(UploadEdited(ftpupload *)));
		e.exec();
	}
}
void Uploads::rmUploadPressed()
{
	int item=getqlbsel(uploads);
	if(item!=-1)
		uploads->removeItem(item);
}
void Uploads::UploadAdded(ftpupload *upload)
{
	ftpxs->addUpload(upload);
	QString ID=upload->getId();
	uploads->insertItem(ID);
	redraw();
}
void Uploads::UploadEdited(ftpupload *)
{
	redraw();
}
void Uploads::redraw()
{
	for(unsigned int i=0;i<uploads->count();i++)
		uploads->removeItem(i);
	ftpupload *u=ftpxs->getFirstUpload();
	while(u!=0) {
		QString s=u->getId();
		uploads->insertItem(s);
		u=ftpxs->getNextUpload(u);
	}
	uploads->update();
}
