#include "pch.h"
#include "BitfieldControlPanel.h"
#include <QSettings>

BitfieldControlPanel::BitfieldControlPanel(QWidget *parent)
	: QWidget(parent)
{
	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);

	layout->addWidget(field);
	field->setAxisLegend("Position", "#SetBits");
	showOptionsButton = new QPushButton("Hide Options");
	layout->addWidget(showOptionsButton);
	connect(showOptionsButton, &QPushButton::pressed, this, &BitfieldControlPanel::toggleOptions);
	layout->addWidget(slider);
	slider->setTitle("Iteration:");
	
	//Connect slider with field
	connect(slider, &RangeSlider::maxChanged, field, &Bitfield::setMaximumIterationToDispaly);
	connect(slider, &RangeSlider::minChanged, field, &Bitfield::setMinimumIterationToDispaly);
	connect(gradient, &ColorGradient::gradientChanged, this, &BitfieldControlPanel::updateDotColorsFromDisplayedRun);

	layout->addWidget(gradient);
	field->frameGraphInView();

	//Settings
	QSettings settings("settings.ini", QSettings::IniFormat, this);
	settings.beginGroup("BitField");
	if (settings.value("hideOptions", true).toBool()) {
		toggleOptions();
	}
	settings.endGroup();
}

BitfieldControlPanel::~BitfieldControlPanel()
{
	//Settings
	QSettings settings("settings.ini", QSettings::IniFormat, this);
	settings.beginGroup("BitField");
	settings.setValue("hideOptions",this->isOptionHidden);
	settings.endGroup();
}

void BitfieldControlPanel::updateDotColorsFromDisplayedRun()
{
	if (!displayedRun || displayedRun->dotsForBitField.empty() || !displayedRun->dotsForBitField.back().existLink()) {
		return;
	}
	for (GraphDataPoint& dot : displayedRun->dotsForBitField) {
		dot.color = gradient->getColorFromValue(dot.orginalPoint->objectiveFunction);
	}
	field->update();
}

void BitfieldControlPanel::displaySingleRun(SingleRun* run)
{
	displayedRun = run;
	updateDotColorsFromDisplayedRun();
	field->removeAll();
	field->addSeries(&run->dotsForBitField, run->name, "", QColor(Qt::black), GraphPlottSeries::SeriesType::Dot);
	if (!run->dotsForBitField.empty() && run->dotsForBitField.back().existLink()) {
		field->maxAmountOfSetBits = run->dotsForBitField.back().orginalPoint->bitVec.size();
		if (run->dotsForBitField.front().orginalPoint->iteration < slider->getMinRange()) {
			slider->setMinRange(run->dotsForBitField.front().orginalPoint->iteration);
		}
		if (run->dotsForBitField.back().orginalPoint->iteration > slider->getMaxRange()) {
			slider->setMaxRange(run->dotsForBitField.back().orginalPoint->iteration);
		}
		
	}
	
	field->frameGraphInView();
}

void BitfieldControlPanel::clearRun()
{
	displayedRun = nullptr;
	field->removeAll();
}

void BitfieldControlPanel::toggleOptions()
{
	this->isOptionHidden = !this->isOptionHidden;
	showOptionsButton->setText(this->isOptionHidden ? "More Options" : "Hide Options");
	this->slider->setHidden(this->isOptionHidden);
	this->gradient->setHidden(this->isOptionHidden);
}
