/*
 * CRfePurRM4RfSettings.cpp
 *
 *  Created on: 12.12.2011
 *      Author: stefan.detter
 */

#include "CRfePurRM4RfSettings.h"
#include <ui_CRfePurRM4Dialog.h>

#include <QInputDialog>
#include <QMessageBox>
#include <QtCore/qmath.h>

#include <reader/QrfeRfePurRM4Reader>
#include <QrfeProgressDialog>


#include "../../permission/Permissions.h"



CRfePurRM4RfSettings::CRfePurRM4RfSettings(Ui::CRfePurRM4DialogClass *dialog, QWidget* parent)
	: QObject(parent)
	, QrfeTraceModule("CRfePurRM4RfSettings")
	, m_ui(dialog)
	, m_parent(parent)
	, m_reader(0)
	, m_sensitivityOffset(0)
{
	setInfoEdit(m_ui->infoEdit);

//	connect(m_ui->setRfSettingsButton,		SIGNAL(clicked()), 			this, SLOT(writeSettings()));
//	connect(m_ui->reloadRfSettingsButton,	SIGNAL(clicked()), 			this, SLOT(reloadSettings()));

	connect(m_ui->attenuationSlider, 		SIGNAL(valueChanged(int)), 	this, SLOT(setAttenuationLabel(int)));

	connect(m_ui->freqAddChannelButton,		SIGNAL(clicked()), 			this, SLOT(addFrequencyEntry()));
	connect(m_ui->freqProfileBox, 			SIGNAL(activated(int)), 	this, SLOT(loadFrequencyProfileTable()));

	m_ui->frequencyTableWidget->setColumnWidth(0, 22);
	m_ui->frequencyTableWidget->setColumnWidth(1, 180);


	m_etsiFrequencies.insert(865.7, true);
	m_etsiFrequencies.insert(866.3, true);
	m_etsiFrequencies.insert(866.9, true);
	m_etsiFrequencies.insert(867.5, true);

    m_etsiUpperFrequencies.insert(916.3, true);
    m_etsiUpperFrequencies.insert(917.5, true);
    m_etsiUpperFrequencies.insert(918.7, true);
    m_etsiUpperFrequencies.insert(919.9, true);

	for(int i = 0; i < 25; i++)
	{
		m_fcc25Frequencies.insert(903.0 + i, true);
	}

	for(int i = 0; i < 50; i++)
	{
		m_fcc50Frequencies.insert(902.75 + (i * 0.50), true);
	}

	m_japanFrequencies.insert(916.8, true);
	m_japanFrequencies.insert(918.0, true);
	m_japanFrequencies.insert(919.2, true);
	m_japanFrequencies.insert(920.4, true);

}

CRfePurRM4RfSettings::~CRfePurRM4RfSettings()
{
}

bool CRfePurRM4RfSettings::init ( QrfeRfePurRM4Reader* reader, QrfeProgressDialog* pb )
{
	m_reader = reader;

	bool ok = readSettingsFromReader(pb);

	loadRfSettings();

	return ok;
}



void CRfePurRM4RfSettings::loadRfSettings( )
{
	const RF_SETTINGS& set = m_settings;

	m_ui->freqProfileBox->setCurrentIndex(0);
	m_ui->freqRandomHoppingBox->setChecked(set.frequencyMode);
	QString freqString;
	m_currentFrequencies.clear();
	foreach(uint freq, set.frequencyList)
	{
		freqString += QString::number(freq) + "\n";
		m_currentFrequencies.insert((double)freq/1000.0, true);
	}
	loadFrequencyProfileTable();

	m_ui->attenuationSlider->setMaximum(set.uhfMaxAttenuation);
	m_ui->attenuationSlider->setValue(set.uhfAttenuation);
	setAttenuationLabel(m_ui->attenuationSlider->value());
	
	m_ui->rfLinkProfile->setCurrentIndex(set.rfLinkProfile);

    m_ui->sessionComboBox->setCurrentIndex(set.session);
    m_ui->targetComboBox->setCurrentIndex(set.target);
    m_ui->selectionComboBox->setCurrentIndex(set.selectionFlag);
    m_ui->phaseValueCheckBox->setChecked(set.phaseValue);
}

bool CRfePurRM4RfSettings::canReadAntennaSpec ( )
{
	return true;
}

void CRfePurRM4RfSettings::readAntennaSpec( )
{
	RF_SETTINGS& set = m_settings;

	set.frequencyList = readFreqeuncyTable();
	set.frequencyMode = m_ui->freqRandomHoppingBox->isChecked();

	set.uhfAttenuation = m_ui->attenuationSlider->value();

	set.rfLinkProfile = m_ui->rfLinkProfile->currentIndex();

    set.session = m_ui->sessionComboBox->currentIndex();
    set.target = m_ui->targetComboBox->currentIndex();
    set.selectionFlag = m_ui->selectionComboBox->currentIndex();
    set.phaseValue = m_ui->phaseValueCheckBox->isChecked();
}




void CRfePurRM4RfSettings::addFrequencyEntry()
{
	bool ok = false;
	double freq = 0;

	if(!Permissions::d->readerFrequencyUnlimited())
	{
        QString regulatory = QInputDialog::getItem(m_parent, "Frequency", "Choose the appropriate regulatory", QStringList() << "ETSI" << "ETSI Upper" << "FCC" << "Japan", 0, false, &ok);
		if(!ok)
			return;

		if(regulatory == "ETSI")
			freq = QInputDialog::getDouble(m_parent, "Frequency", "Insert the new frequency", 866.00, 865.0, 868.0, 2, &ok);
        else if(regulatory == "ETSI Upper")
            freq = QInputDialog::getDouble(m_parent, "Frequency", "Insert the new frequency", 915.00, 921.0, 916.3, 2, &ok);
        else if(regulatory == "FCC")
			freq = QInputDialog::getDouble(m_parent, "Frequency", "Insert the new frequency", 915.00, 902.0, 928.0, 2, &ok);
		else if(regulatory == "Japan")
			freq = QInputDialog::getDouble(m_parent, "Frequency", "Insert the new frequency", 918.00, 916.0, 923.4, 2, &ok);
		else
			return;
	}
	else
		freq = QInputDialog::getDouble(m_parent, "Frequency", "Insert the new frequency", 866.00, 800.0, 1000.0, 3, &ok);

	if(ok){
		m_currentFrequencies.insert(freq, true);
		loadFrequencyProfileTable();
	}
}

void CRfePurRM4RfSettings::loadFrequencyProfileTable()
{
	m_ui->frequencyTableWidget->clearContents();
	m_ui->frequencyTableWidget->setRowCount(0);
	foreach(QCheckBox* box, m_frequencyCheckBoxes)
		delete box;
	m_frequencyCheckBoxes.clear();


	QMap<double, bool>* map = 0;
	switch(m_ui->freqProfileBox->currentIndex())
	{
	case 0:
		map = &m_currentFrequencies;
		m_ui->freqAddChannelButton->setEnabled(true);
		break;
    case 1:
        map = &m_etsiFrequencies;
        m_ui->freqAddChannelButton->setEnabled(false);
        break;
    case 2:
        map = &m_etsiUpperFrequencies;
        m_ui->freqAddChannelButton->setEnabled(false);
        break;
    case 3:
		map = &m_fcc25Frequencies;
		m_ui->freqAddChannelButton->setEnabled(false);
		break;
    case 4:
		map = &m_fcc50Frequencies;
		m_ui->freqAddChannelButton->setEnabled(false);
		break;
    case 5:
		map = &m_japanFrequencies;
		m_ui->freqAddChannelButton->setEnabled(false);
		break;
	}

	if(map == 0)
		return;

	foreach(double freq, map->keys())
	{
		insertInFrequencyTable(map->value(freq), freq);
	}
}

void CRfePurRM4RfSettings::insertInFrequencyTable(bool checked, double frequency)
{
	QCheckBox* box = new QCheckBox(m_ui->frequencyTableWidget);
	m_frequencyCheckBoxes.append(box);
	box->setChecked(checked);

	QTableWidgetItem* frequ = new QTableWidgetItem(QString::number(frequency) + " MHz");

	m_ui->frequencyTableWidget->insertRow(m_ui->frequencyTableWidget->rowCount());
	m_ui->frequencyTableWidget->setCellWidget(m_ui->frequencyTableWidget->rowCount()-1, 0, box);
	m_ui->frequencyTableWidget->setItem(m_ui->frequencyTableWidget->rowCount()-1, 1, frequ);
	m_ui->frequencyTableWidget->setRowHeight(m_ui->frequencyTableWidget->rowCount()-1, 17);
}

QList<uint> CRfePurRM4RfSettings::readFreqeuncyTable()
{
	QList<uint> frequencys;
	for(int i = 0; i < m_ui->frequencyTableWidget->rowCount(); i++)
	{
		if(((QCheckBox*)m_ui->frequencyTableWidget->cellWidget(i, 0))->isChecked())
		{
			QString str = m_ui->frequencyTableWidget->item(i, 1)->text();
			QStringList list = str.split(" ");

			bool ok = false;
			double freq = list.at(0).toDouble(&ok);
			if(!ok)
				continue;

			frequencys.append( (uint) (freq*1000));
		}
	}

	return frequencys;
}




void CRfePurRM4RfSettings::setAttenuationLabel ( int value )
{
	m_ui->attenuationLabel->setText(QString::number(value) + " steps");
}



bool CRfePurRM4RfSettings::writeSettingsToReader( QrfeProgressDialog* pb)
{
	QrfeGlobal::Result res;
	bool err = false;

	readAntennaSpec();

	RF_SETTINGS& set = m_settings;

	res = m_reader->setAttenuation(set.uhfAttenuation);
	if(res == QrfeGlobal::RES_OK)
		infoAppend("OK:  Wrote attenuation");
	else{
		infoAppend("ERR: Could not write attenuation"); err = true;
	}
	pb->increasePorgressBar();

    res = m_reader->setFrequency(set.frequencyMode, set.frequencyList);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Wrote frequency");
    else{
        infoAppend("ERR: Could not write freqeuncy"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->setRfLinkProfile(set.rfLinkProfile);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Wrote rf link profile");
    else{
        infoAppend("ERR: Could not write rf link profile"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->setSession(set.session);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Wrote session");
    else{
        infoAppend("ERR: Could not write session"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->setTarget(set.target);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Wrote target");
    else{
        infoAppend("ERR: Could not write target"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->setSelectionFlag(set.selectionFlag);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Wrote selectionFlag");
    else{
        infoAppend("ERR: Could not write selectionFlag"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->setPhaseValue(set.phaseValue);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Wrote phaseValue");
    else{
        infoAppend("ERR: Could not write phaseValue"); err = true;
    }
    pb->increasePorgressBar();

	if(err)
		showNOK();
	else
		showOK();

	return !err;
}

bool CRfePurRM4RfSettings::readSettingsFromReader( QrfeProgressDialog* pb)
{
	QrfeGlobal::Result res;
	bool err = false;

	RF_SETTINGS& set = m_settings;

	res = m_reader->getAttenuation(set.uhfMaxAttenuation, set.uhfAttenuation);
	if(res == QrfeGlobal::RES_OK)
		infoAppend("OK:  Read attenuation");
	else{
		infoAppend("ERR: Could not read attenuation"); err = true;
	}
	pb->increasePorgressBar();

	res = m_reader->getFrequency(set.frequencyMode, set.freqeuncyMaximum, set.frequencyList);
	if(res == QrfeGlobal::RES_OK)
		infoAppend("OK:  Read frequency");
	else{
		infoAppend("ERR: Could not read frequency"); err = true;
	}
	pb->increasePorgressBar();

    res = m_reader->rfLinkProfile(set.rfLinkProfile);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Read rf link profile");
    else{
        infoAppend("ERR: Could not read rf link profile"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->session(set.session);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Read session");
    else{
        infoAppend("ERR: Could not read session"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->target(set.target);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Read target");
    else{
        infoAppend("ERR: Could not read target"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->selectionFlag(set.selectionFlag);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Read selectionFlag");
    else{
        infoAppend("ERR: Could not read selectionFlag"); err = true;
    }
    pb->increasePorgressBar();

    res = m_reader->phaseValue(set.phaseValue);
    if(res == QrfeGlobal::RES_OK)
        infoAppend("OK:  Read phaseValue");
    else{
        infoAppend("ERR: Could not read phaseValue"); err = true;
    }
    pb->increasePorgressBar();

	return !err;
}
