class_name Balle
extends CharacterBody2D


signal sortie_ecran

const ratio_diff_angle: float = PI * 0.005 # radian / px
const ascension_min: float = 10.0 # px / sec
const vitesse_initiale: float = 100.0 # px / sec
const acceleration_par_touche: float = 50.0 # px / sec / touche

@export var direction_initiale: Vector2 = Vector2.DOWN

var _mouvement: Vector2
var _vitesse: float = vitesse_initiale


func _ready() -> void:
	_mettre_en_mouvement(direction_initiale)


func _physics_process(delta: float) -> void:
	var impact: KinematicCollision2D = move_and_collide(_mouvement * delta)
	if impact != null:
		_rebondir(impact)
		var obstacle: Object = impact.get_collider()
		if obstacle is Raquette:
			_orienter_tir(obstacle)
			_accelerer()
		elif obstacle is Brique:
			_impacter_brique(obstacle)


func _rebondir(impact: KinematicCollision2D) -> void:
	_mouvement = _mouvement.bounce(impact.get_normal())


func _orienter_tir(raquette: Raquette) -> void:
	var difference = global_position.x - raquette.position.x
	_mouvement = Vector2.UP.rotated(difference * ratio_diff_angle) * _mouvement.length()
	
	# empeche la balle de traverser la raquette
	if _mouvement.y > 0:
		_mouvement.y = -ascension_min


func _accelerer() -> void:
	_vitesse += acceleration_par_touche
	_mettre_en_mouvement(_mouvement.normalized())


func _impacter_brique(brique: Brique) -> void:
	brique.frapper(1)


func _mettre_en_mouvement(dir: Vector2) -> void:
	_mouvement = dir * _vitesse


func _auto_detruire() -> void:
	queue_free()


func _quand_verificateur_visibilite_detecte_sortie_ecran():
	sortie_ecran.emit()
	_auto_detruire()
