class_name Brick
extends StaticBody2D


signal kace_broken
signal kace_damaged


var life: int


func setup(x: int, y: int, max_life: int):
	position.x = x * 40
	position.y = y * 20
	life = randi() % max_life + 1
	_refresh_look()


func damage():
	life = life - 1
	emit_signal("kace_damaged")
	if life < 1:
		blow_up()
	else:
		_refresh_look()


func blow_up():
	emit_signal("kace_broken")
	queue_free()


func impact(pos: Vector2):
	damage()


static func color_from_life(n: int) -> Color:
	var x = float(n % 256) / 255
	if n < 256:
		return Color(x, 1.0, 1.0 - x)
	elif n < 512:
		return Color(1.0, 1.0 - x, x)
	elif n < 768:
		return Color(1.0, 0.0, 1.0 - x)
	else:
		return Color(1.0, 0.0, 0.0)

func _refresh_look() -> void:
	modulate = color_from_life(life)
	update() # For custom drawing