#include "Crosshair.h"

using namespace godot;

namespace blitz {
void Crosshair::_bind_methods() {}

Crosshair::Crosshair() :
	m_DotRadius(1.0f),
	m_DotColor(Color(1, 1, 1, 1)),
	m_CrosshairSpeed(0.25f),
	m_CrosshairDistance(2.0f),
	m_Origin(Vector3(0, 0, 0)),
	m_Pos(Vector2(0, 0)) {}
Crosshair::~Crosshair() {}

void Crosshair::_ready() {
	// Catch the parent node directly without SubViewport problem in the editor thx to "recursivity" (if we go up the tree one more
	// notch its bugging)
	Node* root_node = get_parent();
	while (root_node != nullptr && !root_node->is_class("FirstPersonPlayer")) {
		root_node = root_node->get_parent();
	}
	if (root_node != nullptr && root_node->is_class("FirstPersonPlayer")) {
		m_Player = Object::cast_to<FirstPersonPlayer>(root_node);
		DEV_ASSERT(m_Player);
	} else {
		ERR_PRINT("FirstPersonPlayer not found in parent hierarchy.");
	}

	m_CrosshairLines = {Object::cast_to<Line2D>(find_child("Top")), Object::cast_to<Line2D>(find_child("Right")),
		Object::cast_to<Line2D>(find_child("Bottom")), Object::cast_to<Line2D>(find_child("Left"))};
	for (size_t i = 0; i < m_CrosshairLines.size(); i++) {
		DEV_ASSERT(m_CrosshairLines[i]);
	}
	queue_redraw();
}

void Crosshair::_process(float a_Delta) {
	adjust_crosshair_lines();
}

void Crosshair::_draw() {
	draw_circle(Vector2(0, 0), m_DotRadius, m_DotColor);
}

void Crosshair::adjust_crosshair_lines() {
	Vector3 vel = m_Player->get_real_velocity();

	float speed = m_Origin.distance_to(vel);

	m_CrosshairLines[0]->set_position(
		m_CrosshairLines[0]->get_position().lerp(m_Pos + Vector2(0, -speed * m_CrosshairDistance), m_CrosshairSpeed));

	m_CrosshairLines[1]->set_position(
		m_CrosshairLines[1]->get_position().lerp(m_Pos + Vector2(speed * m_CrosshairDistance, 0), m_CrosshairSpeed));

	m_CrosshairLines[2]->set_position(
		m_CrosshairLines[2]->get_position().lerp(m_Pos + Vector2(0, speed * m_CrosshairDistance), m_CrosshairSpeed));

	m_CrosshairLines[3]->set_position(
		m_CrosshairLines[3]->get_position().lerp(m_Pos + Vector2(-speed * m_CrosshairDistance, 0), m_CrosshairSpeed));
}

void Crosshair::set_dot_color(Color a_Color) {
	m_DotColor = a_Color;
	queue_redraw();
}

}  // namespace blitz