#include "Uploads.moc"
#include "EditUpload.h"
#include "AddRCPT.h"
#include <qlabel.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): QWidget(parent,name)
{
	int x=5, y=0;
	int w=640, h=380;
	ftpxs=0;
	uploads=new QListBox(this);
	uploads->setGeometry(x,y,w-10,h-3*uploads->height());
	y+=uploads->height();
	addUpload=new QPushButton(i18n("&Add"),this);
	addUpload->setGeometry(x,y,(w-10)/3,addUpload->height()); x+=(w-10)/3;
	connect(addUpload,SIGNAL(clicked()),SLOT(addUploadPressed()));
	editUpload=new QPushButton(i18n("&Edit"),this);
	editUpload->setGeometry(x,y,(w-10)/3,editUpload->height()); x+=(w-10)/3;
	connect(editUpload,SIGNAL(clicked()),SLOT(editUploadPressed()));
	rmUpload=new QPushButton(i18n("&Remove"),this);
	rmUpload->setGeometry(x,y,(w-10)/3,rmUpload->height());
	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=new EditUpload(0);
	connect(e,SIGNAL(EditUploadDone(ftpupload *)),this,SLOT(UploadAdded(ftpupload *)));
}
void Uploads::editUploadPressed()
{
	int item=getqlbsel(uploads);
	if(item!=-1) {
		EditUpload *e=new EditUpload(ftpxs->getUploadNo(item));
		connect(e,SIGNAL(EditUploadDone(ftpupload *)),this,SLOT(UploadEdited(ftpupload *)));
	}
}
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();
}
