extends Node

class_name GameInstance

signal state_received()

onready var ui := $CanvasLayer/ui
onready var world := $world as GameWorld
onready var systems := $systems as GameSystems
onready var netgame := $"/root/Multiplayer"
onready var physics := world.get_world_2d().direct_space_state as Physics2DDirectSpaceState

var writing := false

func _ready() -> void:
	$"/root/Music/BGM".stop()
	randomize()
	if netgame.hosting:
		world.load_map(netgame.get_current_map())
		world.map.current_ship_position = Vector2(randf() * 1e4, randf() * 1e4)
		world.map.current_ship_target = null
		rpc("spawn_player", 1)
	else:
		world.load_map(GameWorld.Map.EMPTY)
		rpc_id(1, "send_map")
		yield(self, "state_received")
		rpc_id(1, "ready_to_spawn")

master func send_map() -> void:
	var id := get_tree().get_rpc_sender_id()
	var map_data := (world.map as GameMap).serialize()
	var systems_data := systems.serialize()
	print("sending map data to %d" % id)
	rpc_id(id, "receive_data", {
		"map": map_data,
		"systems": systems_data
	})

puppet func receive_data(data: Dictionary) -> void:
	world.map.deserialize(data["map"])
	systems.deserialize(data["systems"])
	print("Received map data from master")
	emit_signal("state_received")

master func ready_to_spawn() -> void:
	var id := get_tree().get_rpc_sender_id()
	print("%d is ready to spawn players" % id)
	
	# Tell him everyone to spawn
	var players := $world/players.get_children()
	for player in players:
		rpc_id(id, "spawn_player", player.get_network_master())

	# Then spawn him as well
	rpc("spawn_player", id)

master func broadcast_zone(message: String, origin: Vector2, radius: float) -> void:
	var shape := CircleShape2D.new()
	shape.radius = radius
	var query := Physics2DShapeQueryParameters.new()
	query.collide_with_areas = true
	query.collide_with_bodies = false
	query.collision_layer = 32
	query.transform.origin = origin
	query.set_shape(shape)
	var res := physics.intersect_shape(query, 100)
	for col in res:
		rpc_id(col.collider.get_network_master(), "add_log", message)

master func broadcast(message: String) -> void:
	rpc("add_log", message)

remotesync func add_log(message: String) -> void:
	ui.logs.add_line(message)

remotesync func spawn_player(id: int) -> void:
	world.spawn_player(id, multiplayer.get_network_unique_id() == id)

remotesync func process_command(cmd: UICommand) -> void:
	match cmd.cmd_type:
		UICommand.CommandType.SetShipTarget:
			world.map.current_ship_target = cmd.cmd_args[0]
