extends Node

# class member variables go here, for example:
# var a = 2
# var b = "textvar"

export (PackedScene) var Mob

export var BASE_HP = 10
export var START_MONEY = 100
export var TOWER_COST = 30
var current_hp = 0
var current_money = 0

func _ready():
	pass

#func _process(delta):
#	# Called every frame. Delta is time since last frame.
#	# Update game logic here.
#	pass

func set_hp(value):
	current_hp = value
	$MainMenu/GameStats/CurrentHealth.text = str(current_hp)
	if current_hp <= 0:
		game_over()

func game_over():
	$Map.stop()
	$MainMenu/GameStats/CurrentHealth.text = "Game over"
	$MainMenu/MarginContainer/VBoxContainer2/HBoxContainer2/LobbyContainer/StartGame.visible = true

func set_money(value):
	current_money = value
	$MainMenu/GameStats/CurrentMoney.text = str(current_money)

sync func start_game():
	set_hp(BASE_HP)
	set_money(START_MONEY)
	$MainMenu/MarginContainer.visible = false
	$MainMenu/GameStats.visible = true
	$Map.start()

func _on_MainMenu_start_game():
	rpc("start_game")


func mob_reached_end():
	set_hp(current_hp-1)

func mob_died():
	set_money(current_money + 3)

func tower_constructed():
	if current_money >= TOWER_COST:
		set_money(current_money - TOWER_COST)


func _on_MainMenu_quit_game():
	get_tree().quit()


func _on_Networking_refresh_lobby():
	$MainMenu.set_lobby($Networking.my_info, $Networking.players)


func _on_MainMenu_host_game():
	$Networking.host_game($MainMenu.get_nickname())


func _on_MainMenu_connect():
	$Networking.connect_to_game($MainMenu.get_nickname(), $MainMenu.get_server_ip())


func _on_Networking_connection_successful():
	$MainMenu.state_connected()


func _on_Networking_connection_failed():
	print("Failed to connect")


func _on_Networking_server_closed():
	$MainMenu.state_main_menu()


func _on_MainMenu_cancel():
	$Networking.reset_connection()


func _on_MainMenu_build_tower():
	$Map.build_tower()

