extends Node2D

export var health_max = 0
onready var health = health_max
signal die
signal damage(dmg)
export(NodePath) var progressbar
export(NodePath) var text
var regen = 0.0
var regen_time = 7
var reactive_dmg = 0.0
var hpmult = 1.0
var buff = 0
export var xpparticles = false
var xp = preload("res://effects/xp.tscn")
var xporbs = 5
var once = true
var chance = 0.0
var invutime = 2.5
var vulnerable = true

func _physics_process(delta):
	$Label.text = str(health)
	buff += 1
	if fmod(buff,regen_time*60) == 00:
		_damage(-regen * health_max ,'',self)

func _damage(dmg, effect, caller):
	if health > health_max: health = health_max
	if vulnerable:
		health -= dmg * hpmult
		health = min(health,health_max)
		emit_signal('damage', dmg)
		if health <= 0 and once:
			once = false
			emit_signal('die')
			if xpparticles: xpanim(caller)
			yield(Timergen.createtime(self,1.0),'timeout')
			caller._expgain(get_parent().exppt)
		effect_processor(effect)
		if has_node(progressbar):
			get_node(progressbar).set_value( health )
			get_node(progressbar).set_max( health_max )
			get_node(text).set_text( str(int(health)) )
		if dmg > 0 : 
			invutime()
			print(get_parent().name + ' entity health is : ' + str(health))

func xpanim(caller):
	for x in xporbs:
		var new = xp.instance()
		new.caller = caller.get_parent()
		get_parent().get_parent().add_child(new)
		new.glob_pos = global_position

func invutime():
	if randf() < chance:
		vulnerable = false
		print('invunerability')
		get_parent().modulate.b = 10
		yield(Timergen.createtime(self,invutime),'timeout')
		print('vunerability')
		vulnerable = true
		get_parent().modulate.b = 1
	else:
		get_parent().modulate = Color(10,10,10)
		yield(Timergen.createtime(self,0.1),'timeout')
		get_parent().modulate = Color(1,1,1)

func _expgain(arg):
	pass

func _ready():
	if has_node(progressbar):
		get_node(progressbar).set_value( health )
		get_node(progressbar).set_max( health_max )
		get_node(text).set_text( str(health_max) )

func effect_processor(effect):
	pass
