#include "Solver.h"

#include "test_assert.h"
#include <cstdlib>
#include <future>
#include <iostream>
#include <vector>

static constexpr int EXECUTION_COUNT = 1000;
static constexpr int KERNEL_CHECKS = 100;
static constexpr int MATRIX_MAX_SIZE = 9;

static const Solver solver;

static int GetRandomInt() {
	return rand() % 11 - 5;
}

#define print_time(i)                                                                                                                 \
	end = std::chrono::system_clock::now();                                                                                           \
	elapsed_seconds = end - start;                                                                                                    \
	std::cout << "elapsed time " << i << " : " << elapsed_seconds.count() << "s" << std::endl;                                        \
	start = std::chrono::system_clock::now()

static unsigned int GetRandomSize() {
	return rand() % MATRIX_MAX_SIZE + 1;
}

static Matrix GetRandomMatrix(std::size_t a_Raw, std::size_t a_Column) {
	Matrix matrix {a_Raw, a_Column};

	for (std::size_t i = 0; i < matrix.GetRawCount(); i++) {
		for (std::size_t j = 0; j < matrix.GetColumnCount(); j++) {
			matrix.at(i, j) = GetRandomInt();
		}
	}

	return matrix;
}

static bool Test() {
	auto start = std::chrono::system_clock::now();
	auto begin = start;
	auto end = start;
	std::chrono::duration<double> elapsed_seconds = end - start;

	std::cout << "Begin\n";

	Matrix matrix = GetRandomMatrix(GetRandomSize(), GetRandomSize());

	print_time(1);

	Matrix copy = matrix;

	Vect kernel = solver.Kernel(std::move(copy));

	print_time(2);

	Matrix nullVector {matrix.GetRawCount(), 1};
	nullVector.Fill(0.0);

	for (std::size_t i = 0; i < kernel.GetCardinal(); i++) {
		Matrix result = matrix * kernel.GetVector(i);
		if(!(result == nullVector)) {
			test_assert(false);
		}
	}

	print_time(3);

	for (std::size_t i = 0; i < KERNEL_CHECKS; i++) {
		Matrix vector = GetRandomMatrix(kernel.GetDimension(), 1);

		test_assert(kernel.IsElementOf(vector) == (matrix * vector == nullVector));
	}

	print_time(4);

	Matrix linearSystem = kernel.GetLinearSystem();

	print_time(5);

	Vect kernel2 = solver.Kernel(std::move(linearSystem));

	test_assert(kernel == kernel2);

	print_time(6);

	elapsed_seconds = end - begin;
	std::cout << "final elapsed time: " << elapsed_seconds.count() << "s" << std::endl;

	std::cout << "End\n";
	return true;
}

int main() {
	srand(time(0));

	std::vector<std::future<bool>> results;

	// appelle la fonction Test() en parallèle
	for (int i = 0; i < EXECUTION_COUNT; i++) {
		auto handle = std::async(std::launch::async, &Test);
		results.push_back(std::move(handle));
		// Test();
	}

	for (auto& result : results) {
		if (!result.get())
			return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
