SettingsDialog::SettingsDialog(QWidget* parent, int flags) 
	: BaseWindow(OnlyCloseButton, NoResize, parent)
	, m_propertyMapper(new SettingsPropertyMapper(this))
	, editRssRule(NULL)
	, deleteRssRule(NULL)
{
	setupUi(this);
	previousFocuse = NULL;
	settings = QApplicationSettings::getInstance();
	rcon = RconWebService::getInstance();
	tracker = TorrentTracker::getInstance();
	FillDTTab();
	FillRestrictionTab();
	FillFilteringGroups();
	FillGeneralTab();
	FillHDDTab();
	FillWebUITab();
	SetupSchedullerTab();
	FillKeyMapTab();
	FillNetworkTab();
	FillRssTab();
	setupCustomWindow();
	QPushButton* applyButton = buttonBox->button(QDialogButtonBox::Apply);
	if (applyButton != NULL)
	{
		applyButton->setEnabled(false);
	}
	setupWindowIcons();
	
	StyleEngene* style = StyleEngene::getInstance();
	connect(style, SIGNAL(styleChanged()), this, SLOT(setupWindowIcons()));
	connect(m_propertyMapper.get(), SIGNAL(GotChanges()), SLOT(EnableApplyButton()));
	connect(m_propertyMapper.get(), SIGNAL(NoChanges()), SLOT(DisableApplyButton()));
}
void SettingsPropertyMapper::ApplyChanges()
{
	for (int i = 0; i < m_propertyInfos.size(); i++)
	{
		PropertyInfo& propertyInfo = m_propertyInfos[i];

		if (propertyInfo.newValue.isValid())
		{
			propertyInfo.valueSetter(propertyInfo.group, propertyInfo.propertyName, propertyInfo.newValue);
			propertyInfo.newValue = QVariant();
		}
	}

	m_hasChanges = false;
	emit NoChanges();
}
void SettingsPropertyMapper::OnEditorCommit()
{
	QWidget* editor = qobject_cast<QWidget*>(sender());
	int propertyInfoIndex = findPropertyInfo(editor);

	if (propertyInfoIndex > -1)
	{
		PropertyInfo& propertyInfo = m_propertyInfos[propertyInfoIndex];
		QVariant originalValue = propertyInfo.valueGetter(propertyInfo.group, propertyInfo.propertyName, propertyInfo.defaultValue);
		QVariant newValue = propertyInfo.uiGetter(propertyInfo.editor, propertyInfo.editorType, propertyInfo.propertyType);

		if (originalValue != newValue)
		{
			propertyInfo.newValue = newValue;

			if (!m_hasChanges)
			{
				emit GotChanges();
				m_hasChanges = true;
			}
		}
		else
		{
			propertyInfo.newValue = QVariant();
			bool hadChnages = m_hasChanges;
			m_hasChanges = false;

			for (int i = 0; i < m_propertyInfos.size(); i++)
			{
				if (m_propertyInfos[i].newValue.isValid())
				{
					m_hasChanges = true;
					break;
				}
			}

			if (hadChnages && !m_hasChanges)
			{
				emit NoChanges();
			}
		}
	}
	else
	{
		qCritical() << "Recived signal from unregisted editor";
	}
}