extends Node


var _server: HttpServer = null
var _userInfo: Dictionary

# This array is of dictionary elements that contain:
#	"online":	Will be true except when used to update the array.
#	"type":		Either "pending" or "known", which is confusing.
#	"ip":		IP address of this peer.
#	"user":		User name on this IP.
#	"refresh":	Do we need to redraw this entry?
var peerArray: Array

	
func _process(_delta):
	pass
	
			
func _ready():
	clear()


func _sort_by_ip(a, b):
	#***TODO*** Sort numerically against last three digits.
	if a["ip"] < b["ip"]:
		return true
	return false
	
	
func clear():
	peerArray.clear()

	
func start_server(address, port, userInfo):
	_userInfo = userInfo
	if _server == null:
		_server = HttpServer.new()
		_server.port = port
		_server.bind_address = address
		_server.server_identifier = "HamNCheese"
		_server.register_router("/", Router.new())
		add_child(_server)
		_server.start()


func stop_server():
	if _server != null:
		_server.stop()
		_server = null
			
	
func update(peersFromCPP: Array):
	var found
	var changed = false
	var oldArray: Array = []
	
	print("\nPeers Raw: ", peersFromCPP)
	print("Peers Before: ", peerArray)
	
	# Remember what we started with.
	oldArray = peerArray.duplicate(true)
	
	# Start a new peer list.
	peerArray.clear()
	
	# Add everyone connected.
	for peerCPP in peersFromCPP:
		# Do we have this peer's information from before?
		found = false
		for oldPeer in oldArray:
			if oldPeer["ip"] == peerCPP["ip"]:
				found = true
				peerCPP = oldPeer
		if !found:
			# We didn't have them.  Add needed records.
			peerCPP["user"]    = ""
			peerCPP["online"]  = true
			peerCPP["refresh"] = false
			changed = true
		# Sometimes the CPP code will return duplicates.  Check.
		# Also check if we need to redraw anyone.
		found = false
		for peer in peerArray:
			if peer["ip"] == peerCPP["ip"]:
				found = true
			if peer["refresh"] == true:
				peer["refresh"] = false
				changed = true
		
		# Add them to the new list.
		peerArray.append(peerCPP)

	# Sort new array.
	peerArray.sort_custom(_sort_by_ip)

	print("Peers After: ", peerArray)

	return changed	
