#include "CGen2SetEPCDialog.h"

#include <QMessageBox>

#include <QrfeGlobal>
#include <tag/QrfeGen2Tag>


#define MAX_EPC_INPUT_LENGTH			20


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


	m_newEpcEdits << ui.newEpc1Edit;
	m_newEpcEdits << ui.newEpc2Edit;
	m_newEpcEdits << ui.newEpc3Edit;
	m_newEpcEdits << ui.newEpc4Edit;


    connect(ui.newEpcSizeSlider, 	SIGNAL(valueChanged(int)),			this, SLOT(newEpcSizeChanged(int)));
    connect(ui.tagIdTextEdit,       SIGNAL(textChanged()),              this, SLOT(textChanged()));

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


}

CGen2SetEPCDialog::~CGen2SetEPCDialog()
{

}

QString CGen2SetEPCDialog::newEPC()
{
	return m_newEPC;
}

int CGen2SetEPCDialog::exec(QrfeGen2Tag* tag)
{
	m_tag = tag;
    m_newEpcSize = m_tag->tagIdBytes().size();

	clearInfo();

    ui.tabWidget->setCurrentIndex(0);

	ui.tagIdEdit->setText(m_tag->tagId());
    ui.tagIdTextEdit->setPlainText(QString::fromLatin1(m_tag->tagIdBytes()));

	bool ok = false;
	m_oldEPC = QrfeGlobal::stringToBytes(ui.tagIdEdit->text(), &ok);
	if(!ok)
		return 0;

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

	int tagIdBytesCount = m_tag->tagIdBytes().count();
	ui.newEpcSizeSlider->setValue(tagIdBytesCount/2);
	setNewEPC(m_tag->tagIdBytes());

	return QDialog::exec();
}

void CGen2SetEPCDialog::newEpcSizeChanged(int newEpcSize)
{
    m_newEpcSize = newEpcSize *= 2;

	QByteArray newEpc = getNewEPC();
	if(newEpc.size() < newEpcSize)
		newEpc.append( QByteArray(newEpcSize - newEpc.size(), (char)0) );
	else
		newEpc = newEpc.left(newEpcSize);

	ui.newEpcSizeLabel->setText(QString::number(newEpcSize) + " Bytes");

	if(newEpcSize == 0)
		ui.zeroLabel->setVisible(true);
	else
		ui.zeroLabel->setVisible(false);

	for(int i = 0; i < m_newEpcEdits.size(); i++)
	{
		QString inputMask;
		int byteCount = qMin(newEpcSize, MAX_EPC_INPUT_LENGTH);

		if(byteCount > 0)
		{
			m_newEpcEdits[i]->setVisible(true);
			for(int j = 0; j < byteCount; j++)
			{
				inputMask.append("HH");
				if(j < byteCount - 1)
					inputMask.append("-");
			}
			inputMask.append(";");
			m_newEpcEdits[i]->setInputMask(inputMask);

			newEpcSize -= byteCount;
		}
		else
		{
			m_newEpcEdits[i]->setVisible(false);
			m_newEpcEdits[i]->setInputMask(";");
		}
	}

	setNewEPC(newEpc);

    if(!m_textChangeActive)
    {
        QString text = ui.tagIdTextEdit->toPlainText();
        if(text.size() > m_newEpcSize)
        {
            text.remove(m_newEpcSize, text.size()-m_newEpcSize);
        }
        ui.tagIdTextEdit->setPlainText(text);

        QTextCursor tmpCursor = ui.tagIdTextEdit->textCursor();
        tmpCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 4);
        ui.tagIdTextEdit->setTextCursor(tmpCursor);
    }
}

void CGen2SetEPCDialog::textChanged()
{
    m_textChangeActive = true;

    QString text = ui.tagIdTextEdit->toPlainText();
    if(text.size() > m_newEpcSize)
    {
        int count = text.size() / 2;
        if((text.size()%2) > 0)
            count++;

        ui.newEpcSizeSlider->setValue(count);
    }

    m_textChangeActive = false;
}

QByteArray CGen2SetEPCDialog::getNewEPC()
{
    QByteArray newBytes;

    if(ui.tabWidget->currentIndex() == 0)
    {
        QString newEPC;
        for(int i = 0; i < m_newEpcEdits.size(); i++)
        {
            if(m_newEpcEdits[i]->text().size() > 0)
            {
                if(i != 0)
                    newEPC += "-";
                newEPC += m_newEpcEdits[i]->text();
            }
        }
        newBytes = QrfeGlobal::stringToBytes(newEPC);
    }
    else
    {
        QString text = ui.tagIdTextEdit->toPlainText();

        QByteArray ascii = text.toLatin1();
        if(ascii.size() < m_newEpcSize)
        {
            QByteArray zeroes((int)m_newEpcSize - ascii.size(), (char)0);
            ascii.append(zeroes);
        }

        newBytes = ascii;
    }

	return newBytes;
}

void CGen2SetEPCDialog::setNewEPC(const QByteArray& epcBytes)
{
	int tagIdBytesCount = epcBytes.count();
	int offset = 0;
	for(int i = 0; i < m_newEpcEdits.size(); i++)
	{
		int byteCount = qMin(tagIdBytesCount, MAX_EPC_INPUT_LENGTH);

		QByteArray t = epcBytes.mid(offset, byteCount);

		m_newEpcEdits[i]->setText("");
		if(t.size() > 0)
			m_newEpcEdits[i]->setText(QrfeGlobal::bytesToString(t));

		offset += byteCount;
		tagIdBytesCount -= byteCount;
	}
}


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

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

    if(ui.tabWidget->currentIndex() == 0)
    {
        bool acceptableInput = true;
        for(int i = 0; i < m_newEpcEdits.size(); i++)
            if( (acceptableInput = m_newEpcEdits[i]->hasAcceptableInput()) == false )
                break;

        if(!acceptableInput)
        {
            QMessageBox::critical(this, "Error", "The new epc is not a valid!");
            return;
        }
    }


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

	m_newEPC = QrfeGlobal::bytesToString(getNewEPC());

	if(getNewEPC() == m_oldEPC){
		QMessageBox::critical(this, "Error", "EPC is the same!\n"
				"Old: " + QrfeGlobal::bytesToString(m_oldEPC) + "\n"
				"New: " + QrfeGlobal::bytesToString(getNewEPC()));
		return;
	}

	QrfeGlobal::TMIResult res = QrfeGlobal::TMI_ERROR;

	res = m_tag->setTagId(m_newEPC, passw);

	if(res == QrfeGlobal::TMI_OK){
		infoSetOK("-- TagId set to " + m_newEPC + " - OK --");
		QMessageBox::information(this, "Set EPC", "Set EPC to " + m_newEPC + ".");
		QDialog::accept();
	}
	else
		handleError(res, "Could not set epc");
}


