extends KinematicBody2D

var motion = Vector2()
var dir = Vector2()
export var speed = 500
var attackrange = 80
signal dieproxy
var exppt = 0
var currentxp = 0
var totalxp = 0
var nextxp = 25
var lv = 1



func get_stat(arg):
	var buff = 1.0
	for x in Powerups.dict.values():
		if x.has(arg):
			buff *= x[arg]
	print(arg +" stat is : "+ str(buff))
	return buff

func _ready():
	
	self.speed = get_stat('speed') * 200
	self.xpmult = get_stat('xpmult')
	$hitbox.dmg = get_stat('dmg') * 10
	$hitbox.critical_chance = get_stat('critical_chance') - 1.0
	$hitbox.critical_dmg = get_stat('critical_dmg')
	$Health.reactive_dmg = get_stat('dmg') * get_stat('react_dmg')
	$Health.hpmult = get_stat('hppickup')
	$Health.chance = (get_stat('invunerabilitychance') - 1.0)
	$Health.chance += ((get_stat('invunerabilitychancemult') - 1.0)*self.speed/100)
	$Health.invutime = get_stat('invunerabilitytime')
	$hitbox.hpsteal = get_stat('hpsteal')
	$hitbox.stealhp = get_stat('stealhp')
	$hitbox.apc = get_stat('atkspeed')
	$Health.regen = get_stat('regen') - 1
	$Health.health = get_stat('hp') * 50
	$Health.health_max = get_stat('hp') * 50
	$Camera2D.zoom.x = get_stat('camzoom')
	$Camera2D.zoom.y = get_stat('camzoom')
	$Health._ready()
	print('real invu chance is : ' + str($Health.chance))
	self.attackrange =  get_stat('range') * 80

	
	for x in get_node("Icon").get_children():
		for y in x.get_children():
			for z in y.get_children():
				z.queue_free()
			var sprite = Sprite.new()
			sprite.hframes = 2
			sprite.texture = Powerups.dict[y.name].img
			y.add_child(sprite)

func _physics_process(delta):
	
	move_and_slide(motion * speed)
	$hitbox.position = dir * attackrange
	$Icon.rotation = atan2(motion.y,motion.x)
	$AnimationPlayer.playback_speed = motion.length() * speed / 100 * 1.5

func _input(event):
	if event is InputEventScreenDrag or event is InputEventScreenTouch and event.is_pressed():
		dir = (event.position - get_global_transform_with_canvas().origin).normalized()
		motion = dir
#	else:
#		motion *= .8
		

func _on_Health_die():
	emit_signal('dieproxy')
	pass # Replace with function body.

var xpmult = 1.0
signal level_up

func _on_hitbox_gotxp(arg):
	totalxp += arg * xpmult
	currentxp += arg * xpmult
	if currentxp > nextxp:
		currentxp -= nextxp
		emit_signal("level_up")
		nextxp += 5
		lv += 1
		print(lv)
	$CanvasLayer/VBoxContainer/Label.set_text(str(int(currentxp)))
	$CanvasLayer/VBoxContainer/Label3.set_text('Lv.'+str(lv))
	$CanvasLayer/VBoxContainer/Label/ProgressBar2.set_value( currentxp )
	$CanvasLayer/VBoxContainer/Label/ProgressBar2.set_max( nextxp )
	pass # Replace with function body.
