#include <time.h>
#include "../common/vector.h"
#include "../common/misc.h"
#include "simulation.h"
#include "../common/debug.h"
#include "solvers.h"
#include <stdio.h>

extern scene_data* main_scene;

int current_sim = EULER;
int sim_type = -1;

//tracks the state of the cannon or the spring
state current;
state *current_state = &current;

double sim_step_size = 0.1;

void capture_state(state *s)
{
	FILE *dump_file;
	
	printd(NORMAL, "pos: %f, %.2f, %.2f\n",
		   s->position.x, s->position.y, s->position.z);
	printd(NORMAL, "vel: %.2f, %.2f, %.2f\n",
		   s->velocity.x, s->velocity.y, s->velocity.z);


	dump_file = fopen("dump.csv","a");
	fprintf(dump_file, "%f\n", s->position.y);
	fclose(dump_file);
}

void save_ball_data(int index1, int index2, double index3, double index4, double value)
{
	FILE *dump_file;
	
	printd(NORMAL, "obj: %i, tes: %i, minr: %.1f, maxr: %.1f, %.2f\n", index1, index2, index3, index4, value*10000);

	dump_file = fopen("dump.csv","a");
	fprintf(dump_file, "%i, %i, %f, %f, %f\n", index1, index2, index3, index4, value*10000); //in microseconds
	fclose(dump_file);
}

void multiply_state(state *dest, state *s, double d)
{
	multiply_vector(&dest->position, &s->position, d);
	multiply_vector(&dest->velocity, &s->velocity, d);
}

void add_states(state *dest, state *s1, state *s2)
{
	add_vectors(&dest->position, &s1->position, &s2->position);
	add_vectors(&dest->velocity, &s1->velocity, &s2->velocity);
}

void run_simulation()
{
	if(sim_type == T_CANNON)
		run_cannon();
	else if(sim_type == T_SPRING)
		run_spring();
	else if(sim_type == T_BALLS)
		run_balls();
}

void start_sim()
{
	if(sim_type == T_CANNON)
	{
		fire_cannon();
	}
	else if(sim_type == T_SPRING)
	{
		release_spring();
	}
}

void change_solver()
{
	if(current_sim == EULER)
	{
		current_sim = MIDPOINT;
		printd(NORMAL, "Using Midpoint");
	}
	else if(current_sim == MIDPOINT)
	{
		current_sim = RK4;
		printd(NORMAL, "Using RK4");
	}
	else
	{
		current_sim = EULER;
		printd(NORMAL, "Using Euler");
	}
}


void reset_sim()
{
	if(sim_type == T_CANNON)
	{
		reset_cannon_state();
	}
	else if(sim_type == T_SPRING)
	{
		reset_spring_state();
	}

}
