extends Node

var net = NetworkedMultiplayerENet.new()
var api = MultiplayerAPI.new()
var port = 1909
var maxplayer = 100
#var cert = load('user://Certificate/x509_Certificate.crt')
#var key = load('user://Certificate/x509_Key.key')

func _ready():
	print('Login listening to port: ' + str(port))
	net.create_server(port, maxplayer)
#	net.set_dtls_key(key)
#	net.set_dtls_certificate(cert)
#	net.set_dtls_enabled(true)
	self.set_custom_multiplayer(api)
	custom_multiplayer.set_root_node(self)
	custom_multiplayer.set_network_peer(net)
	
#	net.connect("peer_disconnected",self,"disc")
	net.connect("peer_connected",self,"conn")
	pass # Replace with function body.

func _process(_delta):
	custom_multiplayer.poll()

var playerphsyics = preload('res://playerphysics.tscn')

func conn(id):
	print('login client connected, id: ' + str(id))

export(NodePath) var PostgreSQL

remote func RegisterPlayer(username, password, password2, email, salt, requester):
	var db = get_parent().get_node('PostgreSQL')
	var message = 'registering...'
	if password != password2:
		message = 'passwords are not equal'
	var email_check = db.Read('login_database','email',"'"+email+"'")
	var username_check = db.Read('login_database','username',"'"+username+"'")
	if email_check != []: message = 'this email is already registered'
	if username_check != []: message = 'soemone already has this username'
	print(message)
	rpc_id(api.get_rpc_sender_id(), 'update_status', message)
	if message != 'registering...': return
	for i in 1024: password = (password+salt).sha256_text()
	print('adding new data to the login db...')
	db.Create('login_database',['email','username','password','salt','creation_date'],[email, username, password, salt, str(OS.get_unix_time())])

remote func salt_request(username):
	var db = get_parent().get_node('PostgreSQL')
	print('salt requested... by ' + str(username))
	var salt = db.Read('login_database','username',"'"+username+"'")
	print(salt)
	rpc_id(api.get_rpc_sender_id(), 'salt_arrived', salt[0][4])

remote func password_confirmation(username,password, salt):
	var message = 'login...'
	var db = get_parent().get_node('PostgreSQL')
	for i in 1024: password = (password+salt).sha256_text()
	var password_db = db.Read('login_database','username',"'"+username+"'")[0][3]
	print(salt)
	print(password)
	print(password_db)
	if password != password_db: message = 'password or username is wrong'
	rpc_id(api.get_rpc_sender_id(), 'update_status', message)
	if message != 'login...': return
	var ip = api.get_peer_address(api.get_rpc_sender_id())
	print(ip)
	var token = ( username+ip+str(OS.get_unix_time())).sha256_text()
	db.Delete('validtokens_database',"username", "'"+username+"'")
	db.Create('validtokens_database',['username','token','ip','creation_date'],[username, token, ip, str(OS.get_unix_time())])
	rpc_id(api.get_rpc_sender_id(), '_on_servertoken', token, username)
	print(message)
