extends Node

var ConsoleService
var NetworkService

func _ready():
	NetworkService = $"/root/NetworkService"
	ConsoleService = $"/root/ConsoleService"
	NetworkService.connect("on_client_connected", self, "on_client_connected")
	NetworkService.connect("on_server_connected", self, "on_server_connected")
	NetworkService.connect("on_server_disconnected", self, "on_server_disconnected")

func on_client_connected(id: int):
	if NetworkService.NETWORK_MODE == 'server':
		var server_mods = get_local_mods()
		rpc_id(id, "compute_needed_mods", server_mods)
		
func get_local_mods():
	var md5_hashes = []
	for mod_desc in ModService.mod_arr:
		if not mod_desc.md5: continue
		md5_hashes.push_back(mod_desc.md5)
	return md5_hashes

remote func send_mods_to_client(id: int, needed_mods: Array):
	var ModService = $"/root/ModService"
	for mod_desc in ModService.mod_arr:
		if not needed_mods.has(mod_desc.md5):
			continue
		if mod_desc.type != 'zip':
			continue
		var mod_file = File.new()
		mod_file.open(mod_desc.path, 1)
		var file_length = mod_file.get_len()
		var bytes = mod_file.get_buffer(file_length)
		ConsoleService.log("Sending mod "+mod_desc.name+" with size: "+String(bytes.size()/1000000)+"MB")
		rpc_id(id, "receive_mod", mod_desc.name, bytes)

remote func compute_needed_mods(server_mods: Array):
	var needed_mods_md5 = server_mods
	var dir = Directory.new()
	var err = dir.make_dir_recursive('user://servers/'+NetworkService.server_hash+'/mods')
	var mod_dir_exists = dir.open('user://servers/'+NetworkService.server_hash+'/mods')
	dir.list_dir_begin()

	while true:
		var file = dir.get_next()
		var basename = file.get_basename()
		if file == "":
			break
		if file.ends_with(".zip") and server_mods.has(basename):
			needed_mods_md5.erase(basename)

	dir.list_dir_end()
	
	rpc_id(1, 'send_mods_to_client', get_tree().get_network_unique_id(), needed_mods_md5)

remote func receive_mod(name: String, bytes: PoolByteArray):
	ConsoleService.log("Receiving mod "+name+" with size: "+String(bytes.size()/1000000)+"MB")
	var file_path = 'user://servers/'+NetworkService.server_hash+'/mods/'+name+'.zip'
	var dir_path = file_path.get_base_dir()
	var mod_file = File.new()
	var dir = Directory.new()
	var err = dir.make_dir_recursive(dir_path)
	mod_file.open(file_path, 2)
	mod_file.store_buffer(bytes)
	mod_file.close()
	dir.rename(file_path, dir_path+'/'+mod_file.get_md5(file_path)+'.zip')

func on_server_connected():
	pass
	
func on_server_disconnected():
	pass
