extends Node
export (PackedScene) var Creature
export (float) var mutation_rate = 0.05

var selected = []
var rng = RandomNumberGenerator.new()

func _ready():
	rng.randomize()
	var p0 = get_node("../GUI/Parent0")
	var p1 = get_node("../GUI/Parent1")
	p0.text = ""
	p1.text = ""
	pass
	
func spawn_a_bitch():
	var c = Creature.instance()
	add_child(c)
	
	# Geef de bitch een random positie en rotatie
	#c.rotate_y(rand_range(-5, 5))
	c.transform = Transform(c.transform.basis, Vector3(rand_range(-17, 17), 0, rand_range(-30, 0)))
	c.set_color()
	return c
	
func kill_a_bitch():
	var c = get_child(get_child_count()-1)
	if c:
		c.queue_free()
	#remove_child(c)

func combine_a_bitch():
	if selected.size() == 2:
		var new_dna = []
		for i in range(selected[0].dna.size()):
			if rng.randf() > 0.5:
				new_dna.append(selected[0].dna[i])
			else:
				new_dna.append(selected[1].dna[i])
			if rng.randf() <= mutation_rate:
				new_dna.append(!new_dna.pop_back())
		var new_child = spawn_a_bitch()
		new_child.dna = new_dna
		deselect_all()
		select(new_child)
		new_child.describe()
		new_child.set_color()

func select_changed_hook():
	var p0 = get_node("../GUI/Parent0")
	var p1 = get_node("../GUI/Parent1")
	p0.text = ""
	p1.text = ""
	var preview0 = get_node("../GUI/Preview0/Viewport")
	var preview1 = get_node("../GUI/Preview1/Viewport")
	for i in range(1, preview0.get_child_count()):
		preview0.remove_child(preview0.get_child(i))
	for i in range(1, preview1.get_child_count()):
		preview1.remove_child(preview1.get_child(i))
	if selected.size() >= 1:
		p0.text = selected[0].describe()
		var copy0 = selected[0].duplicate()
		copy0.get_node("AnimationPlayer").set_autoplay("Animation")
		copy0.transform = Transform(copy0.transform.basis, Vector3(0, 0, 0))
		preview0.add_child(copy0)
	if selected.size() >= 2:
		p1.text = selected[1].describe()	
		var copy1 = selected[1].duplicate()
		copy1.get_node("AnimationPlayer").set_autoplay("Animation")
		copy1.transform = Transform(copy1.transform.basis, Vector3(0, 0, 0))
		preview1.add_child(copy1)

func deselect_all():
	for i in range(selected.size()):
		selected[i].get_node("SelectionIndicator").visible = false;
	selected = []
	select_changed_hook()

func select(creature):
	if selected.has(creature):
		creature.get_node("SelectionIndicator").visible = false;
		selected.erase(creature)
	else:	
		selected.append(creature)
		creature.get_node("SelectionIndicator").visible = true;
	select_changed_hook()	

func select_a_bitch(camera, event, click_position, click_normal, index, creature_id):
	if event.is_action_pressed("select_creature"):
		var kindeke = get_child(creature_id)
		select(kindeke)
		print(creature_id)
