extends Node2D


var bringmanScene = preload("res://scenes/bringman.tscn")

onready var btnAdd = get_node("btnAdd")
onready var city_parent = get_node("city_parent")
onready var market_parent = get_node("market_parent")
onready var bringman_parent = get_node("bringman_parent")
onready var money_frame = get_node("moneyframe")

onready var button_diam = btnAdd.texture.get_width()*btnAdd.transform.get_scale().x


func _ready():
	randomize()


func _input(event):
	if event is InputEventMouseButton and event.button_index == BUTTON_LEFT && event.pressed:
		if (event.position - btnAdd.position).length() < button_diam/2:
			spawn()


func spawn():
	var market = random_market()
	var city = random_city()
	
	var bm = bringmanScene.instance()
	
	var rot = rand_range(-TAU/5, +TAU/5)
	
	var vec_start = Vector2(0, 1).rotated(rot)
	
	var diag = sqrt(2*pow(button_diam/2, 2))
	
	bm.position = btnAdd.position + (vec_start * -(button_diam/2 - bm.radius()))
	bm.spawn    = btnAdd.position + (vec_start * -(diag + bm.radius()))
	bm.market = market.get_path()
	bm.city = city.get_path()
	bm.company = btnAdd.get_path()
	bm.moneyframe = money_frame.get_path()
	
	bringman_parent.add_child(bm)


func random_market():
	var r = []
	for child in market_parent.get_children():
		r.append(child)
	return r[randi() % r.size()]


func random_city():
	var r = []
	for child in city_parent.get_children():
		r.append(child)
	return r[randi() % r.size()]







