#include "CRfePurReflectedPowerSettings.h"

#include <reader/QrfeRfePurReader>

CRfePurReflectedPowerSettings::CRfePurReflectedPowerSettings(QTextEdit* infoEdit, QWidget* parent)
    : ReaderTabWidget(tr("Reflected Power Settings"), parent)
    , m_reader(0)
{
	ui.setupUi(this);
	setInfoEdit(infoEdit);

    connect(ui.rfpSettingsButton,			SIGNAL(clicked()),
            this, 							  SLOT(setRfpMeasurementData()));
}

CRfePurReflectedPowerSettings::~CRfePurReflectedPowerSettings()
{

}

bool CRfePurReflectedPowerSettings::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();

	return true;
}

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

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

    reloadSettings();
}

void CRfePurReflectedPowerSettings::reloadSettings()
{
    uchar time = 0;
    uchar cycles = 0;
    short threshold = 0;
    if(m_reader->autoReflectedPowerMeasurementData(time, cycles, threshold) != QrfeGlobal::RES_OK)
    {
        ui.rfpMeasurementTimeBox->setEnabled(false);
        ui.rfpMeasurementCountBox->setEnabled(false);
        ui.rfpThresholdBox->setEnabled(false);
        ui.rfpSettingsButton->setEnabled(false);
    }
    else
    {
        ui.rfpMeasurementTimeBox->setEnabled(true);
        ui.rfpMeasurementCountBox->setEnabled(true);
        ui.rfpThresholdBox->setEnabled(true);
        ui.rfpSettingsButton->setEnabled(true);

        ui.rfpMeasurementTimeBox->setValue(time*10);
        ui.rfpMeasurementCountBox->setValue(cycles);
        ui.rfpThresholdBox->setValue(threshold / 100);
    }
}

void CRfePurReflectedPowerSettings::setRfpMeasurementData()
{
    if(m_reader == 0)
        return;

    uchar time = ui.rfpMeasurementTimeBox->value() / 10;
    uchar cycles = ui.rfpMeasurementCountBox->value();
    short threshold = ui.rfpThresholdBox->value() * 100;
    QrfeGlobal::Result res = m_reader->setAutoReflectedPowerMeasurementData(time, cycles, threshold);
    if(res == QrfeGlobal::RES_OK)	{
        infoSetOK("-- Set auto rfp data to " + QString::number(time) + "," + QString::number(cycles) + "," + QString::number(threshold) + " --");
    }
    else {
        infoSetError("-- Could not set auto rfp data --");
    }

    reloadSettings();
}



