#include "insert_win.h"
#include <QMessageBox>

InsertWin::InsertWin(QWidget * p):QDialog(p),prev_num(1) {
	setupUi(this);

	connect(buttonBox, SIGNAL(accepted()), this, SLOT(saveLast()));
	connect(buttonBox, SIGNAL(accepted()), this, SLOT(myAccept()));
	connect(n_spinBox, SIGNAL(valueChanged(int)), this, SLOT(setPrvky(int)));
	connect(prvek_spinBox, SIGNAL(valueChanged(int)), this, SLOT(changePrvek(int)));

	connect(I_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeTyp(int)));
}

void InsertWin::changePrvek(int num) {
	if (num <= 0) 
		return ;

	if (prev_num != num) {
		prvky[prev_num-1]->sila = (I_comboBox->currentIndex() == 0 ? SILA : MOMENT);
		prvky[prev_num-1]->x = x_doubleSpinBox->value();
		prvky[prev_num-1]->SP = SP_doubleSpinBox->value();
		prvky[prev_num-1]->alfa = alfa_doubleSpinBox->value();
	}
	
	I_comboBox->setCurrentIndex(prvky[num-1]->sila ? 0 : 1);
	x_doubleSpinBox->setValue(prvky[num-1]->x);
	SP_doubleSpinBox->setValue(prvky[num-1]->SP);
	alfa_doubleSpinBox->setValue(prvky[num-1]->alfa);

	prev_num = num;
}

void InsertWin::setPrvky(int num) {
	while (!prvky.isEmpty())
		delete prvky.takeFirst();
	for (int i = 0; i < num; i++) 
		prvky.append(new PRVEK);

	if (num > 0) {
		prev_num = 1;
		prvek_spinBox->setRange(1,num);
		prvek_horizontalScrollBar->setRange(1,num);
		prvek_spinBox->setValue(1);

		prvek_horizontalScrollBar->setEnabled(true);
		prvek_spinBox->setEnabled(true);
		groupBox->setEnabled(true);
	}
	else {
		prvek_spinBox->setRange(0,0);
		prvek_horizontalScrollBar->setRange(0,0);
		prvek_spinBox->setValue(0);

		prvek_horizontalScrollBar->setDisabled(true);
		prvek_spinBox->setDisabled(true);
		groupBox->setDisabled(true);
	}
}

void InsertWin::resetAll() {
	l_doubleSpinBox->setValue(0.0);
	n_spinBox->setValue(0);
}

void InsertWin::saveLast() {
	if (n_spinBox->value() > 0) {
		prvky[prvek_spinBox->value()-1]->sila = (I_comboBox->currentIndex() == 0 ? SILA : MOMENT);
		prvky[prvek_spinBox->value()-1]->x = x_doubleSpinBox->value();
		prvky[prvek_spinBox->value()-1]->SP = SP_doubleSpinBox->value();
		prvky[prvek_spinBox->value()-1]->alfa = alfa_doubleSpinBox->value();
	}
}

void InsertWin::myAccept() {
	if (n_spinBox->value() == 0) 
		QMessageBox::warning(this,"projekt","Nebyl zadan zadny silovy prvek.",QMessageBox::Close);
	else accept();
}

void InsertWin::changeTyp(int sila) {
	if (sila == 0) { // nastav SILA
//		SP_doubleSpinBox->setMinimum(0.0);
		alfa_doubleSpinBox->setDisabled(false);
	}
	else { // nastav MOMENT
//		SP_doubleSpinBox->setMinimum(-1E11);
		alfa_doubleSpinBox->setDisabled(true);
	}
}
