#include <stdio.h>
#include <stdbool.h>
#include <GL/glew.h>
#include <math.h>

#include "matrixMath.h"


#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KNRM  "\x1B[0m"

#define EPSILON 0.001f

int exitCode = 0;

void printTest(char* name, bool result) {
	if (result) {
		printf("%s    PASSED%s - %s\n", KGRN, KNRM, name);
	} else {
		printf("%s!!! FAILED%s - %s\n", KRED, KNRM, name);
		exitCode = 1;
	}
}

void testSumDiff() {
	mat3 A = {1, 0, 0, -1, 0, -1, 1, -1, 9};
	mat3 B = {0, 1, -1, 0, 0, 1, 1, -1, 8};
	GLfloat target = 7;

	GLfloat value = mat3SumDiff(&A, &B);

	bool result = fabs(value - target) < EPSILON;

	if (!result) {
		printf("\nA:\n");
		mat3Print(&A);
		printf("\nB:\n");
		mat3Print(&B);
		printf("target: %f\n", target);
		printf("value: %f\n", value);
	}

	printTest("mat3SumDiff", result);
}

void testMat3Minor() {
	mat3 M = {2, 0, 1, -1, 5, -1, 3, 2, -2};
	mat3 target = {-8, 5, -17, -2, -7, 4, -5, -1, 10};

	mat3Minor(&M, &M);

	printTest("mat3Minor", mat3SumDiff(&M, &target) < EPSILON);
}

void testMat3Cofactor() {
	mat3 M = {2, 0, 1, -1, 5, -1, 3, 2, -2};
	mat3 target = {-8, -5, -17, 2, -7, -4, -5, 1, 10};

	mat3Cofactor(&M, &M);

	printTest("mat3Cofactor", mat3SumDiff(&M, &target) < EPSILON);
}

void testMat3Adjoint() {
	mat3 M = {1, 2, -1, 2, 1, 2, -1, 2, 1};
	mat3 target = {-3, -4, 5, -4, 0, -4, 5, -4, -3};


	mat3Adjoint(&M, &M);

	printTest("mat3Adjoint", mat3SumDiff(&M, &target) < EPSILON);
}

void testMat3MultiplyScalar() {
	mat3 M = {1, 2, 3, 4, 0, -1.5f, -2.5f, -3.5f, -4.5f};
	GLfloat x = 0.9f;
	mat3 target = {0.9f, 1.8f, 2.7f, 3.6f, 0, -1.35f, -2.25f, -3.15f, -4.05f};

	mat3MultiplyScalar(&M, &M, x);

	printTest("mat3MultiplyScalar", mat3SumDiff(&M, &target) < EPSILON);
}

void testMat3Determinant() {
	mat3 M = {1, -3, 2, 3, -1, 3, 2, -3, 1};
	GLfloat target = -15;

	printTest("mat3Determinant", fabs(mat3Determinant(&M) - target) < EPSILON);
}

void testMat3Inverse() {
	mat3 M = {1, 2, -1, 2, 1, 2, -1, 2, 1};
	mat3 target = {0.1875f, 0.25f, -0.3125f, 0.25f, 0, 0.25f, -0.3125f, 0.25f, 0.1875f};

	mat3Inverse(&M, &M);

	bool result = mat3SumDiff(&M, &target) < EPSILON;

	if (!result) {
		printf("\nM:\n");
		mat3Print(&M);
		printf("\ntarget:\n");
		mat3Print(&target);
	}

	printTest("mat3Inverse", result);
}

void testMat3Transpose() {
	mat3 M = {1, 2, 3, 4, 5, 6, 7, 8, 9};
	mat3 target = {1, 4, 7, 2, 5, 8, 3, 6, 9};

	mat3Transpose(&M, &M);

	printTest("mat3Transpose", mat3SumDiff(&M, &target) < EPSILON);
}

int main(void) {
	testSumDiff();
	testMat3Minor();
	testMat3Cofactor();
	testMat3Adjoint();
	testMat3MultiplyScalar();
	testMat3Determinant();
	testMat3Inverse();
	testMat3Transpose();

	return exitCode;
}