#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ExtendedVector.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow) {
    ui->setupUi(this);
}

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

void parseAsDoubleVector(QString vec_string, vector<double> *vec) {
    QStringList vec_string_list = vec_string.split(",");
    bool isSuccess;
    double t_value;
    for (auto vec_it = vec_string_list.begin(); vec_it != vec_string_list.end(); vec_it++) {
        t_value = vec_it->toDouble(&isSuccess);
        if (isSuccess) {
            vec->push_back(t_value);
        } else {
            throw std::invalid_argument("Please only write doubles into the Input field.");
            return;
        }
    }
    return;
}

void printVector(vector<double> vec, QTextStream *output) {
    *output << "< ";
    for (auto it = vec.begin(); it != vec.end()-1; it++) {
        *output << *it << ", ";
    }
    *output << *(vec.end()-1) << " >" << Qt::endl;
}

void addTestToOutput(vector<double> vec, double factor, QTextStream *output) {
    *output << "Maximum: " << ExtendedVector::max(vec) << Qt::endl;
    *output << "Are all values positive? " << ExtendedVector::allPositive(vec) << Qt::endl;
    vector<double> product_vector = ExtendedVector::product(vec, factor);
    *output << "Product: ";
    printVector(product_vector, output);
    *output << "Norm: " << ExtendedVector::norm(vec) << Qt::endl;
    vector<double> vec_copy = vec;
    ExtendedVector::normalise(vec_copy);
    *output << "Normalisation: " << Qt::endl;
    printVector(vec_copy, output);
}

void MainWindow::on_okButton_clicked() {
    QString vec1_string =  ui->vec1Input->text();
    QString vec2_string = ui->vec2Input->text();
    vector<double> vec1;
    vector<double> vec2;
    parseAsDoubleVector(vec1_string, &vec1);
    parseAsDoubleVector(vec2_string, &vec2);
    QString owo = "";
    QTextStream output(&owo);
    output << "Vector 1: " << Qt::endl;
    addTestToOutput(vec1, ui->factorSpinBox->value(), &output);
    output << Qt::endl << "Vector 2: " << Qt::endl;
    addTestToOutput(vec2, ui->factorSpinBox->value(), &output);
    output << Qt::endl << "Scalarproduct: " << ExtendedVector::product(vec1, vec2) << Qt::endl;

    ui->outputBrowser->setText(*output.string());
}

