//
// C++ Implementation: plugincontroldlgmeditator
//
// Description: 
//
//
// Author: Benjamin Mesing <bensmail@gmx.net>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "plugincontroldlgmeditator.h"

#include <iostream>

#include <QHeaderView>
#include <QTableWidget>
#include <QTableWidgetItem>

// NPlugin
#include "pluginmanager.h"

#include <helpers.h>

#include "ui_plugincontrol.h"

using namespace std;

namespace NPlugin {

PluginControlDlgMeditator::PluginControlDlgMeditator(PluginManager* pPluginManager)
{
	_pPluginManager = pPluginManager;
	_pPluginDisplay = 0;
}


PluginControlDlgMeditator::~PluginControlDlgMeditator()
{
}

QString PluginControlDlgMeditator::pluginName(int row)
{
	return _pPluginDisplay->item(row, 0)->text();
}

QString PluginControlDlgMeditator::pluginDirectory(int row)
{
	return _pPluginDisplay->item(row, 3)->text();
}


void PluginControlDlgMeditator::displayDialog(QWidget* pParent)
{
	typedef PluginManager::PluginData PluginData;
	QDialog dlg(pParent);
	Ui::PluginControl uiDlg;
	uiDlg.setupUi(&dlg);
 	_pPluginDisplay = uiDlg._pPluginDisplay;
	_pPluginDisplay->verticalHeader()->hide();
	vector<PluginData> plugins = _pPluginManager->getAvailablePlugins();
	_pPluginDisplay->setRowCount(plugins.size());
	int row = 0;
	for (vector<PluginData>::iterator it = plugins.begin(); it != plugins.end(); ++it, ++row)
	{
		const PluginData& pd = *it;
		QTableWidgetItem* pItem = new QTableWidgetItem(toQString(pd.name()));
		_pPluginDisplay->setItem(row, 0, pItem);
		pItem->setFlags(Qt::ItemIsUserCheckable | pItem->flags());
		pItem->setCheckState( (pd.pPlugin == 0) ? Qt::Unchecked : Qt::Checked);
		pItem = new QTableWidgetItem(toQString(pd.version()));
		_pPluginDisplay->setItem(row, 1, pItem);
		pItem = new QTableWidgetItem(toQString(pd.author()));
		_pPluginDisplay->setItem(row, 2, pItem);
		pItem = new QTableWidgetItem(toQString(pd.directory));
		_pPluginDisplay->setItem(row, 3, pItem);
	}
	connect(_pPluginDisplay, SIGNAL(cellChanged(int, int)), SLOT(onCellChanged(int, int)));

	dlg.exec();
	_pPluginDisplay = 0;
}



void PluginControlDlgMeditator::onCellChanged(int row, int column)
{
	QString pluginName = this->pluginName(row);
	QTableWidgetItem* pItem = _pPluginDisplay->item(row, column);
	// if the plugin was requested to be loaded, and it was not loaded before
	if (pItem->checkState() == Qt::Checked && !_pPluginManager->isLoaded(pluginName))
	{
		if (_pPluginManager->loadPlugin(toString(pluginDirectory(row)), toString(pluginName)) == 0)
			pItem->setCheckState(Qt::Unchecked);
	}
	else if (pItem->checkState() == Qt::Unchecked && _pPluginManager->isLoaded(pluginName))
	{
		_pPluginManager->unloadPlugin(toString(pluginName));
	}
}

}
