#include "CRfePurAS399XRegisterTable.h"

#include <QStandardItemModel>

#include <reader/QrfeRfePurReader>
#include <as399x/AS399X_Defines.h>

CRfePurAS399XRegisterTable::CRfePurAS399XRegisterTable(QTextEdit* infoEdit, QWidget* parent)
	: ReaderTabWidget(tr("AS399X Register"), parent)
    , m_reader(0)
{
	ui.setupUi(this);
	setInfoEdit(infoEdit);

	connect(ui.readRegisterButton, 			SIGNAL(clicked()),
			this, 							  SLOT(readAS399xRegister()));

	m_as399xRegisterModel = new QStandardItemModel(this);
	m_as399xRegisterModel->setColumnCount(2);
	ui.registerTableView->setModel(m_as399xRegisterModel);
}

CRfePurAS399XRegisterTable::~CRfePurAS399XRegisterTable()
{
}

bool CRfePurAS399XRegisterTable::init(QrfeReaderInterface* reader)
{
	m_reader = qobject_cast<QrfeRfePurReader*>(reader);
	if( m_reader == 0 )
		return false;

	ulong sw_rev = m_reader->softwareRevision();
	sw_rev &= 0x0000FFFF;
	if(sw_rev < 0x0027)
		return false;

	clearInfo();
	clearRegisterTable();

	return true;
}

void CRfePurAS399XRegisterTable::deinit()
{
	m_reader = 0;
}

void CRfePurAS399XRegisterTable::activated()
{
    if(m_reader == 0)
        return;
}

void CRfePurAS399XRegisterTable::readAS399xRegister()
{
	if(m_reader == 0)
		return;

	QByteArray regs;
	QrfeGlobal::Result res = m_reader->as399xRegister(regs);
	if(res == QrfeGlobal::RES_OK)	{
		infoSetOK("-- Read the register from the chip --");
		infoAppend("Read: " + regs.toHex());
	}
	else {
		infoSetError("-- Could not read register --");
	}

	m_as399xRegisterModel->clear();
	m_as399xRegisterModel->setColumnCount(2);

	uchar addr = 0;
	uchar offset = 0;
	QStringList verticalHeader;
	while(offset < (regs.size() -1) )
	{
		if(regs.size() == 0)
			return;

		verticalHeader << QString("0x%1").arg(addr, 2, 16, QChar('0'));

		QStandardItem* item;

		item = new QStandardItem(AS399X_Defines::regAddrToString(addr));
		m_as399xRegisterModel->setItem(addr, 0, item);

		QByteArray data = regs.mid(offset, AS399X_Defines::regSize(addr));
		offset += AS399X_Defines::regSize(addr);
		QByteArray temp;
		for(int i = 0; i < data.size(); i++)
			temp.push_front(data.at(i));
		item = new QStandardItem("0x" + QString(temp.toHex()));
		m_as399xRegisterModel->setItem(addr, 1, item);

		addr++;
	}

	m_as399xRegisterModel->setVerticalHeaderLabels(verticalHeader);
	ui.registerTableView->verticalHeader()->setVisible(true);
	ui.registerTableView->horizontalHeader()->setStretchLastSection(true);
}

void CRfePurAS399XRegisterTable::clearRegisterTable()
{
	m_as399xRegisterModel->clear();
	m_as399xRegisterModel->setColumnCount(2);
	ui.registerTableView->verticalHeader()->setVisible(false);
	ui.registerTableView->horizontalHeader()->setStretchLastSection(true);
}
