extends RigidBody2D

export(int) var damage
export(String) var weapon_name
export(int) var durability = 5
export(int) var stab_times = 1

const TIME_SLEEP = 3.0
const TEST_COUNT = 5

var parent = null
var time_live = 60
var time_test = 0
var tests = 0

func clear_collision_masks():
	collision_mask = 0

func _physics_process(delta):
	time_live -= delta
	
	# test for minimal damping, when object can't sleep
	var vel_length = linear_velocity.length()
	
	if !sleeping and vel_length > 0 and vel_length < 2.5:
		time_test += delta
		
		if time_test > 0.3:
			tests += 1
			time_test = 0
			
			if tests == TEST_COUNT:
				time_live = 0
	
	if time_live <= 0:
		queue_free()

func _on_Weapon_sleeping_state_changed():
	clear_collision_masks()
	time_live = TIME_SLEEP

func _on_Weapon_body_shape_entered(body_id, body, body_shape, local_shape):
	if body is TileMap:
		global.add_particles("Sparks", position, 0)
		durability =- 1
		
		if durability == 0:
			queue_free()
			
		return
		
	if body.has_method("apply_damage"):
		body.apply_damage(position, body_shape, parent, damage, weapon_name)
		
		stab_times -= 1
		
		if stab_times == 0:
			queue_free()