#include "CGen2SetPasswordDialog.h"

#include <QMessageBox>

#include <tag/QrfeGen2Tag>

CGen2SetPasswordDialog::CGen2SetPasswordDialog(QWidget *parent)
    : QDialog(parent)
{
	ui.setupUi(this);
	setInfoEdit(ui.infoEdit);

	connect(ui.okButton, 			SIGNAL(clicked()), 					this, SLOT(tryAccept()));
	connect(ui.cancelButton, 		SIGNAL(clicked()), 					this, SLOT(reject()));
}

CGen2SetPasswordDialog::~CGen2SetPasswordDialog()
{

}


int CGen2SetPasswordDialog::exec(QrfeGen2Tag* tag)
{
	m_tag = tag;

	ui.tagIdEdit->setText(m_tag->tagId());

	ui.currentPasswordLineEdit->setText("00-00-00-00");
	ui.newPasswordLineEdit->setText("00-00-00-00");

	ui.typeBox->setCurrentIndex(1);

	return QDialog::exec();
}

void CGen2SetPasswordDialog::tryAccept()
{
	clearInfo();

	if(!ui.currentPasswordLineEdit->hasAcceptableInput())
	{
		QMessageBox::critical(this, "Error", "The current password is not a valid!");
		return;
	}
	if(!ui.newPasswordLineEdit->hasAcceptableInput())
	{
		QMessageBox::critical(this, "Error", "The new password is not a valid!");
		return;
	}


	bool ok = false;
	QByteArray currentPassw = QrfeGlobal::stringToBytes(ui.currentPasswordLineEdit->text(), &ok);
	if(!ok)
	{
		QMessageBox::critical(this, "Error", "The current password is not a valid!");
		return;
	}
	QByteArray newPassw = QrfeGlobal::stringToBytes(ui.newPasswordLineEdit->text(), &ok);
	if(!ok)
	{
		QMessageBox::critical(this, "Error", "The new password is not a valid!");
		return;
	}

	QrfeGlobal::TMIResult res = QrfeGlobal::TMI_ERROR;

	if(ui.typeBox->currentIndex() == 0)
		res = m_tag->setKillPassword(currentPassw, newPassw);
	else if(ui.typeBox->currentIndex() == 1)
		res = m_tag->setAccessPassword(currentPassw, newPassw);

	if(res == QrfeGlobal::TMI_OK){
		QString action;
		infoSetOK("-- Set " + ui.typeBox->currentText() + " Password of tag " + ui.tagIdEdit->text() + " - OK -- ");
		QMessageBox::information(this, "Set password", "Set " + ui.typeBox->currentText() + " Password of tag " + ui.tagIdEdit->text());
		QDialog::accept();
	}
	else
		handleError(res, "Could not set password");

}




