#include "bat.hpp"
#include "environment.hpp"
#include "key_positions_structure.hpp"
#include "interpolation.hpp"
#include "terrain.hpp"

void bat::initialize_mvt(vec3 p, numarray<vec3> key_positions, numarray<float> key_times)
{
	for (int i = 0; i < key_positions.size(); i++) {
		key_positions[i] += p;
	}

	// Initialize the helping structure to display/interact with these positions
	keyframe.initialize(key_positions, key_times);

	// Set timer bounds
	// The timer must span a time interval on which the interpolation can be conducted
	// By default, set the minimal time to be key_times[1], and the maximal time to be key_time[N-2] (enables cubic interpolation)
	int NT = key_times.size();
	timer_mvt.t_min = key_times[0];
	timer_mvt.t_max = key_times[NT - 1];
	//make the bat start somewhere on its descent
	timer_mvt.t = rand_interval(timer_mvt.t_min, key_times[1]/2);

	//Set max HP and current HP
	max_hp = 5;
	hp = 5;
	
	//No death_time currently
	death_time = -1;

	//bat hitbox
	bat_hitbox.initialize_hitbox(2, {{0,2.5*size,0},{0,-1.75*size,0.5*size}}, { size*3, size * 1.5});
}

void bat::update_mvt()
{
	// Update the current time
	timer_mvt.update();
	float t = timer_mvt.t;

	// clear trajectory when the timer restart
	if (t < timer_mvt.t_min + 0.1f)
		keyframe.trajectory.clear();

	// Forget there was a first point so it goes in circles once third point is passed
	if (t > keyframe.key_times[2] && timer_mvt.t_min == 0)
	{
		timer_mvt.t_min = keyframe.key_times[1];
		numarray<vec3> key_positions;
		numarray<float> key_times;
		int n = keyframe.key_positions.size() - 1;
		key_positions.resize(n);
		key_times.resize(n);
		for (int i = 0; i < n; i++) {
			key_positions[i] = keyframe.key_positions[i + 1];
			key_times[i] = keyframe.key_times[i + 1];
		}
		keyframe.key_positions = key_positions;
		keyframe.key_times = key_times;
	}

	if (t + 0.1f > timer_mvt.t_max) pos_futur = interpolation(timer_mvt.t_min + 0.01f, keyframe.key_positions, keyframe.key_times, 0.5f);
	else pos_futur = interpolation((t + 0.1f), keyframe.key_positions, keyframe.key_times, 0.5f);

	// Compute the interpolated position
	pos = interpolation(t, keyframe.key_positions, keyframe.key_times, 0.5f);
}