extends Node

func Create(db,key,value):
	print(key)
	print(value)
	var truncatekey = ''
	var truncatevalue = ''
	for i in key.size()-1:
		truncatekey += str(key[i]) + ','
	for i in value.size()-1:
		truncatevalue += "'"+str(value[i])+"'" + ','
	
	truncatekey += key.back()
	truncatevalue += "'"+str(value.back())+"'"
	
	print(truncatekey)
	print(truncatevalue)
	
	var db_command = ("""
	insert into %s (%s) values (%s);
	""" % [db, truncatekey, truncatevalue])
	print(db_command)
	database.execute(db_command)

func Read(db, key, value):
	var db_command = ("""
	select * from %s where %s = %s;
	""" % [db, key, value])
	print(db_command)
	var datas := database.execute(db_command)
	var ret
	for data in datas:
		ret = (data.data_row)
	return ret

func Update(db, key, value, wherekey, wherevalue):
	var db_command = ("""
	update %s set %s = %s where %s = %s;
	""" % [db, key, value, wherekey, wherevalue])
	print(db_command)
	database.execute(db_command)

func Delete(db, key, value):
	var db_command = ("""
	delete from %s where %s = %s;
	""" % [db, key, value])
	print(db_command)
	database.execute(db_command)

var database := PostgreSQLClient.new()

const USER = "godot"
const PASSWORD = "godotisfree"
const HOST = "localhost"
const PORT = 5432 # Default postgres port
const DATABASE = "godot" # Database name

func _ready():
	print('Database is being loaded...')
	var _error := database.connect("connection_established", self, "_executer")
	_error = database.connect("authentication_error", self, "_authentication_error")
	_error = database.connect("connection_closed", self, "_close")
	_error = database.connect_to_host("postgresql://%s:%s@%s:%d/%s" % [USER, PASSWORD, HOST, PORT, DATABASE])

func _physics_process(_delta: float) -> void:
	database.poll()

func _authentication_error(error_object: Dictionary) -> void:
	prints("Error connection to database:", error_object["message"])

func _executer() -> void:
	database.execute("""
	create table login_database( 
		id serial primary key,
		email varchar(64) unique not null,
		username varchar(64) unique not null,
		password varchar(64) not null,
		salt varchar(64) not null,
		creation_date varchar(64) not null
	);
	""")
	
	database.execute("""
	create table validtokens_database( 
		id serial primary key,
		username varchar(64) not null,
		token varchar(64) unique not null,
		ip varchar(64) not null,
		creation_date varchar(64) not null
	);
	""")
#	print('readitng data test')
#	print(Read('validtokens_database','username',"'22222222'"))
#	Create('niggers',["crime","executiondate"],["'das rite'","'2017-06-01'"])
#	Update('niggers',"executiondate","'2019-08-07'" , "crime", "'das rite'")
#	print(Read('niggers',"crime","'das rite'"))
#	Delete('niggers',"crime","'das rite'")
#	print(Read('niggers',"crime","'das rite'"))

func _close(clean_closure := true) -> void:
	prints("DB CLOSE,", "Clean closure:", clean_closure)


func _exit_tree() -> void:
	print('closing')
	database.close()
