extends Node

signal on_client_connected;
signal on_server_connected;
signal on_server_disconnected;

var NETWORK_MODE = "client"
var local_server_pid = null
var server_hash = null

func _ready():
	get_tree().connect("network_peer_connected", self, "server_on_peer_connected")
	get_tree().connect("connected_to_server", self, "client_on_connection_succeeded")
	get_tree().connect("connection_failed", self, "client_on_connection_failed")
	self.connect("tree_exiting", self, "cleanup_local_server")

func create_local_server():
	local_server_pid = OS.execute(OS.get_executable_path(), ["--mode=server", "--port=9801"], false)
	
func cleanup_local_server():
	if local_server_pid:
		OS.kill(local_server_pid)
	
func get_local_connection():
	return {"host": "127.0.0.1", "port": 9801}

func init_server(port: int):
	NETWORK_MODE = "server"
	var peer = NetworkedMultiplayerENet.new()
	peer.create_server(port, 256)
	get_tree().set_network_peer(peer)


func init_client(host: String, port: int):
	NETWORK_MODE = "client"
	server_hash = (host+String(port)).md5_text()
	var peer = NetworkedMultiplayerENet.new()
	peer.create_client(host, port)
	get_tree().set_network_peer(peer)
	
func server_on_peer_connected(id: int):
	emit_signal("on_client_connected", id)

func client_on_connection_succeeded():
	emit_signal("on_server_connected");

func client_on_connection_failed():
	emit_signal("on_server_disconnected", "Connection Failed")

