#include "plugins_list.h"
#include "SH_plugins_loader.h"
#include "ui_plugins_list.h"
#include "plugins_list_item.h"
#include "SH_runtime.h"
#include "SH_plugins_manager.h"
#include <QScrollBar>
#include <QMetaMethod>




SHPluginsList::SHPluginsList(QWidget * parent): QWidget(parent) {
	Q_INIT_RESOURCE(plugins);
	ui = new Ui::SHPluginsList();
	ui->setupUi(this);
	ui->progressBar->hide();
	//tree->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
	connect(ui->buttonClose, SIGNAL(clicked(bool)), this, SIGNAL(closeRequest()));
	connect(ui->buttonReload, SIGNAL(clicked(bool)), this, SIGNAL(reloadPluginsRequest()));
	if (RUNTIME->plugins_manager) {
		connect(&RUNTIME->plugins_manager->webInterface(), &SHPluginsWeb::downloadStarted, this, [this](){ui->progressBar->show();});
		connect(&RUNTIME->plugins_manager->webInterface(), &SHPluginsWeb::downloadProgress, this, [this](int p){ui->progressBar->setValue(p);});
		connect(&RUNTIME->plugins_manager->webInterface(), &SHPluginsWeb::downloadFinished, this, [this](){ui->progressBar->hide();});
		connect(RUNTIME->plugins_manager, &SHPluginsManager::infoChanged, this, [this](){updateList();});
	}
	//connect(SHCORE, SIGNAL(changedPlugins()), this, SLOT(updateList()));
}


SHPluginsList::~SHPluginsList() {
	delete ui;
}


void SHPluginsList::showEvent(QShowEvent * e) {
	updateList();
	QWidget::showEvent(e);
}


void SHPluginsList::updateList() {
	if (!RUNTIME->plugins_manager) return;
	QAD::CursorOverrider curov;
	int ppos = ui->tree->verticalScrollBar()->value();
	ui->tree->clear();
	auto pl = RUNTIME->plugins_manager->allPlugins();
	for (const auto & p: pl) {
		auto * ti = new QTreeWidgetItem();
		auto pli = new SHPluginsListItem();
		ui->tree->addTopLevelItem(ti);
		ui->tree->setItemWidget(ti, 0, pli);
		pli->setPlugin(p);
	}
	filterList();
	ui->tree->verticalScrollBar()->setValue(ppos);
}


void SHPluginsList::filterList() {
	QString filter = ui->lineFilter->text();
	for (int i = 0; i < ui->tree->topLevelItemCount(); ++i) {
		auto * ti = ui->tree->topLevelItem(i);
		auto * w = qobject_cast<SHPluginsListItem * >(ui->tree->itemWidget(ti, 0));
		if (!w) continue;
		ti->setHidden(!w->isFilterMatch(filter));
	}
}


void SHPluginsList::on_buttonGet_clicked() {
	if (RUNTIME->plugins_manager)
		RUNTIME->plugins_manager->webInterface().requestPluginsList();
}


void SHPluginsList::on_buttonUpdateAll_clicked() {
	if (RUNTIME->plugins_manager)
		RUNTIME->plugins_manager->updateAll();
}


void SHPluginsList::on_buttonUpdateSelected_clicked() {
	if (!RUNTIME->plugins_manager) return;
	QStringList names;
	auto sil = ui->tree->selectedItems();
	for (auto * ti: sil) {
		auto * w = qobject_cast<SHPluginsListItem * >(ui->tree->itemWidget(ti, 0));
		if (!w) continue;
		names << w->name();
	}
	RUNTIME->plugins_manager->update(names);
}
