#include "CGen2StoreText.h"

#include <QMessageBox>

#include <tag/QrfeGen2Tag>


CGen2StoreText::CGen2StoreText(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()));
}

CGen2StoreText::~CGen2StoreText()
{

}

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

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

	ui.passwordLineEdit->setText("00-00-00-00");

	m_tag->readFromTag( QrfeGen2Tag::MEM_USER, 0, QByteArray(4, (char)0), 0, m_storedText);
	ui.textBrowser->setText(QString::fromLatin1(m_storedText));
	ui.lineEdit->setMaxLength(m_storedText.size());
	ui.lineEdit->clear();

	clearInfo();
	showOK();

	return QDialog::exec();
}

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

	if(ui.lineEdit->text().size() == 0)
	{
		QDialog::accept();
		return;
	}

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

	QString newText = ui.lineEdit->text();

	bool ok = false;
	QByteArray passwd = QrfeGlobal::stringToBytes(ui.passwordLineEdit->text(), &ok);
	if(!ok)
	{
		QMessageBox::critical(this, "Error", "The access password is not a valid!");
		return;
	}

	QByteArray toStore = ui.lineEdit->text().toLatin1();
	toStore.append( QByteArray(m_storedText.size() - toStore.size(), (char)'\0') );

	QrfeGlobal::TMIResult res = QrfeGlobal::TMI_ERROR;

	res = m_tag->writeToTag(QrfeGen2Tag::MEM_USER, 0, passwd, toStore);

	if(res == QrfeGlobal::TMI_OK){
		infoSetOK("-- Stored the text: \"" + toStore + "\" - OK -- ");
		QMessageBox::information(this, "Store text", "Stored the text \"" + toStore + "\" successful.");
		QDialog::accept();
	}
	else
		handleError(res, "Could not store text");
}
