extends Spatial
export var bonfire: PackedScene
export var fence: PackedScene
export var gate: PackedScene
export var bed: PackedScene
export var pillory: PackedScene
export var gibbet: PackedScene
export var tent: PackedScene

func _ready():
	call_deferred("update_camp")

func update_camp():
	for c in get_children():
		c.queue_free()
	var camp_level = scenario.camp_level
	var prisoners = []
	var beds = 1
	var tents = 0
	if scenario.camp_level < 50:
		beds = max(1, scenario.camp_level)
	else:
		beds = 50
	var bandits = scenario.bandits_count
	var circ = 32.0 + 2.0 * scenario.camp_level
	var r = circ / (2.0 * PI)
	var angle = 2.0 * PI / (circ / 2.0)
	var angle_bed = 2.0 * PI / (circ / 4.0)
	var a = 0.0
	var bf = bonfire.instance()
	add_child(bf)
	bf.transform = Transform(Basis(), Vector3(0, 0.08, 0))
	var beds_r =  2.5
	var tents_r = 0.0
	if camp_level > 25:
		beds_r = max(min(12.0, r), r / 2.0)
		tents_r = 5.5
		tents = camp_level - 25
		beds = max(0, beds - 2 * tents)
		r = max(max(r, beds_r + 6.5), tents_r + 6.5)
		circ = r * 2.0 * PI
	var beds_to_place = beds
	var k = 0
	var tents_to_place = tents
	while tents_to_place > 0:
		a = 0.0
		while a < 2.0 * PI:
			if tents_to_place > 0:
				var tent_pt = Vector3(tents_r * cos(a), 0.08 , tents_r * sin(a))
				var tent_xform = Transform(Basis().rotated(Vector3.UP, -a + PI / 2.0), tent_pt)
				var b = tent.instance()
				add_child(b)
				b.transform = tent_xform
				tents_to_place -= 1
			var n = int((tents_r * 2.0 * PI) / 8.0)
			a += 2.0 * PI / float(n)
		tents_r += 5.5
		k += 1
	k = 0
	if beds_r <= tents_r + 1.5:
		beds_r = tents_r + 1.5

	while beds_to_place > 0:
		a = 0.0
		while a < 2.0 * PI:
			if beds_to_place > 0:
				var bed_pt = Vector3(beds_r * cos(a), 0.08 , beds_r * sin(a))
				var bed_xform = Transform(Basis().rotated(Vector3.UP, -a + PI / 2.0), bed_pt)
				var b = bed.instance()
				add_child(b)
				b.transform = bed_xform
				beds_to_place -= 1
			var n = (beds_r * 2.0 * PI) / 2.0
			a += 2.0 * PI / n
		beds_r += 2.5
		k += 1
	a = 0.0
	if r - max(beds_r, tents_r) < 3.0:
		r = max(beds_r, tents_r) + 3.0
		circ = r * 2.0 * PI
		circ = floor(circ / 4.0) * 4.0
		r = circ / 2.0 / PI
	while a < 2.0 * PI - 0.05:
		var obj = fence
		if a == 0.0:
			obj = gate
		var pt = Vector3(r * cos(a), 0 , r * sin(a))
		var xform = Transform(Basis().rotated(Vector3.UP, -a + PI / 2.0), pt)
		var f = obj.instance()
		add_child(f)
		f.transform = xform
		a += 2.0 / circ * 2.0 * PI
func _physics_process(delta):
	var space: PhysicsDirectSpaceState = get_world().get_direct_space_state()
	var from = global_transform.origin - Vector3.UP * 200.0
	var to = global_transform.origin + Vector3.UP * 200.0
	var result = space.intersect_ray(from, to)
	if result.has("collider"):
		global_transform.origin = result.position
		set_physics_process(false)
		scenario.emit_signal("spawn_player", global_transform)

