#include "core/session.h"
#include "core/strings.h"
#include "gui/dialog/settings.h"
#include "track/types.h"
#include <QListWidget>
#include <QListWidgetItem>
#include <QGroupBox>
#include <QCheckBox>
#include <QLabel>
#include <QSizePolicy>
#include <QVBoxLayout>
#include <algorithm>

Q_DECLARE_METATYPE(Track::Types::MediaPlayer);

QWidget* SettingsPageRecognition::CreatePlayersWidget() {
	QWidget* result = new QWidget(this);
	result->setAutoFillBackground(true);
	result->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);

	QVBoxLayout* full_layout = new QVBoxLayout(result);

	{
		/* URLs */
		QGroupBox* group = new QGroupBox(tr("Media players"), result);
		group->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);

		QVBoxLayout* group_layout = new QVBoxLayout(group);

		{
			/* Feed link */
			QWidget* widget = new QWidget(group);
			QVBoxLayout* widget_layout = new QVBoxLayout(widget);

			QCheckBox* checkbox = new QCheckBox(group);
			checkbox->setText(tr("Enable media player detection"));
			widget_layout->addWidget(checkbox);

			{
				QLabel* label = new QLabel(tr("Allowed media players:"), widget);
				widget_layout->addWidget(label);
			}

			{
				QListWidget* listwidget = new QListWidget(widget);
				for (size_t i = 0; i < players.size(); i++) {
					const auto& player = players[i];
					{
						QListWidgetItem* item = new QListWidgetItem(listwidget);
						item->setCheckState(player.GetEnabled() ? Qt::Checked : Qt::Unchecked);
						item->setText(Strings::ToQString(player.GetName() + " (" + player.GetExecutable() + ")"));
						item->setData(Qt::UserRole, QVariant::fromValue(i));
					}
				}
				connect(listwidget, &QListWidget::itemChanged, this, [this](QListWidgetItem* item){
					if (!item)
						return;
					size_t i = item->data(Qt::UserRole).toUInt();
					players[i].SetEnabled(item->checkState());
				});
				/* this is down here because the listwidget state depends on it */
				connect(checkbox, &QCheckBox::stateChanged, this, [this, listwidget](int state) {
					detect_media_players = (state == Qt::Checked);
					listwidget->setEnabled(detect_media_players);
				});
				listwidget->setEnabled(detect_media_players);

				widget_layout->addWidget(listwidget);
			}

			group_layout->addWidget(widget);
		}

		full_layout->addWidget(group);
	}

	full_layout->setSpacing(10);
	full_layout->addStretch();

	return result;
}

void SettingsPageRecognition::SaveInfo() {
	session.config.recognition.detect_media_players = detect_media_players;
	session.recognition.players = players;
}

SettingsPageRecognition::SettingsPageRecognition(QWidget* parent)
	: SettingsPage(parent, tr("Recognition")),
	  players(session.recognition.players) {
	detect_media_players = session.config.recognition.detect_media_players;
	AddTab(CreatePlayersWidget(), tr("Media players"));
}
