#include "enemy_car.hpp"
#include "godot_cpp/classes/navigation_agent3d.hpp"
#include "utils/game_root.hpp"
#include "utils/godot_macros.h"

namespace godot {
void EnemyCar::_bind_methods() {
#define CLASSNAME EnemyCar
    GDSIGNAL("damage");
}

void EnemyCar::_enter_tree() {
    CarPhysics::_enter_tree();
    GDGAMEONLY();
    this->player = Object::cast_to<CarPlayer>(GameRoot3D::get_singleton()->get_players()[0]->to_node());
    this->agent = this->get_node<NavigationAgent3D>("NavigationAgent3D");
}

void EnemyCar::_process(double delta_time) { GDGAMEONLY();
    this->process_navigate();
}

void EnemyCar::process_navigate() {
    --this->next_recalc;
    if(this->next_recalc <= 0)
        this->recalculate_navigation();
    Vector3 const target_direction{this->agent->get_next_path_position() - this->get_global_position()};
    Vector3 const direction{this->get_global_basis().get_column(2)};
    float const ang_dif = target_direction.signed_angle_to(direction.normalized(), this->get_global_basis().get_column(1));
    this->set_target_speed(this->max_speed);
    this->set_current_steering(Math::abs(ang_dif) * this->steering_speed);
    this->set_brake(target_direction.length() < this->brake_distance);
}

void EnemyCar::recalculate_navigation() {
    this->next_recalc = this->recalc_frame_interval;
    this->agent->set_target_position(this->player->get_global_position() + this->player->get_global_basis().get_column(2) * 4.f);
}
}
