extends Weapon

const DAMAGE: float = 100.0
const HEAT_DAMAGE: float = 10.0
const BULLET_COLLISION_MASK: int = 0x00000001

var _charged: bool = false

@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var muzzle: Node3D = $Muzzle

@onready var rifle_beam_scene: PackedScene = load("res://src/effects/rifle_beam/rifle_beam.tscn")


func fire() -> void:
	# XXX: can we refactor shared logic with autocannon?
	if aimcast.is_colliding():
		var past_target: Vector3 = 2 * aimcast.get_collision_point() - muzzle.global_position
		var collision: Dictionary = get_world_3d().direct_space_state.intersect_ray(
			PhysicsRayQueryParameters3D.create(
				muzzle.global_position, past_target, BULLET_COLLISION_MASK, _excluded_rid
			)
		)
		if collision:
			@warning_ignore("unsafe_cast")
			var target: Node3D = collision["collider"] as Node3D
			if target is DamageableBody:
				(target as DamageableBody).deal_damage(DAMAGE)
				(target as DamageableBody).deal_heat(HEAT_DAMAGE)

			var beam: RifleBeam = rifle_beam_scene.instantiate()
			var point: Vector3 = collision["position"]
			beam.look_at_from_position(muzzle.global_position, point)
			beam.endpoint = point
			GameState.game_map.add_child(beam)


func trigger() -> void:
	animation_player.play("charge")


func release() -> void:
	if _charged:
		_charged = false
		print("WHAM!!!")
		animation_player.play("fire")
		fire()
	else:
		# sad trombone
		animation_player.play_backwards("charge")


func deactivate() -> void:
	_charged = false
	animation_player.stop()
