
#include "returndialog.h"
#include "qdvd.h"
#include "mainwindow.h"

#include <iostream.h>
#include <stdio.h>

#include <qlabel.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qhbox.h>
#include <qvgroupbox.h>
#include <qdatetime.h>

ReturnDialog::ReturnDialog(
	QWidget *parent,
	const char *name)
	: QDialog(parent, name, true) // TODO: MAKE FALSE
{
	QVBoxLayout *main	= new QVBoxLayout(this, 4, 4);
	QHBoxLayout *bottom	= new QHBoxLayout;

	QVGroupBox *returnbox = new QVGroupBox("List of Disk IDs to Return", this);
	QHBox *topbox = new QHBox(returnbox);
	topbox->setSpacing(4);
	QLabel *l = new QLabel("Disk ID:", topbox);
	l->setFixedSize(l->sizeHint());
	m_pDiskId = new QSpinBox(0, 100000, 1, topbox);
	QPushButton *add = new QPushButton("Add", topbox);
	connect(add, SIGNAL(clicked()), this, SLOT(add()));

	m_pList = new QListView(returnbox);
	m_pList->addColumn("Disk ID");
	m_pList->addColumn("Title");
	m_pList->addColumn("Member No");
	m_pList->addColumn("Status");
	
	QPushButton *remove = new QPushButton("Remove", returnbox);
	connect(remove, SIGNAL(clicked()), this, SLOT(remove()));
	QPushButton *retDVD	= new QPushButton("Return", this);
	connect(retDVD, SIGNAL(clicked()), this, SLOT(returnDVD()));
	QPushButton *cancel	= new QPushButton("Cancel", this);
	connect(cancel, SIGNAL(clicked()), this, SLOT(close()));

	bottom->addStretch();
	bottom->addWidget(retDVD);
	bottom->addWidget(cancel);
	
	main->addWidget(returnbox);
	main->addLayout(bottom);

	main->activate();
}


ReturnDialog::~ReturnDialog()
{
}


void
ReturnDialog::add()
{
	int member_id;
	char date_rented[9];
	dvd_title dvd;
	int disk_id = m_pDiskId->value();

	dvd_rented_disk_info(disk_id, &member_id, date_rented);
	int rc = dvd_title_get(disk_id, &dvd);

	if(rc == 0 && member_id > 0)
	{
		QListViewItem *item;
		
		item = new QListViewItem(m_pList);
		item->setText(0, QString::number(disk_id));
		item->setText(1, dvd.title_text);
		item->setText(2, QString::number(member_id));

		if(isOverdue(date_rented))
			item->setText(3, "OVERDUE");
		else
			item->setText(3, "Ok");
	}
}


void
ReturnDialog::remove()
{
	delete m_pList->selectedItem();
}


void
ReturnDialog::returnDVD()
{
	QListViewItem *item = m_pList->firstChild();
	int member_id;
	char date[9];
	QString log;

	while(item != 0)
	{
		dvd_disk_return(item->text(0).toInt(), &member_id, date);
		log.sprintf("Returned disk: %s",
					(const char *)item->text(0));
		MainWindow::addLog(log);
		item = item->nextSibling();
	}
	
	accept();
}


bool
ReturnDialog::isOverdue(
	const char *date_rented) const
{
	int year, month, day;
	sscanf(date_rented, "%04d%02d%02d",  &year, &month, &day);

	QDate d(year, month, day);

	return QDate::currentDate() < d;
}

