import sqlite3

#from sqlite3.dbapi2 import Cursor

# Start einer Userklasse
# Lade, sofern vorhanden, Spieler aus der Datenbank


class User:
	__usercount = 0
	__highscore = 0
	__uid = -1
	__username = ""
	__db_player_exist = 0
	__lastlogin = ""
	__played_time = 0
	__all_listed_users = list()	
	#__sql_create_table = "CREATE TABLE IF NOT EXISTS user ( `id` INTEGER PRIMARY KEY, `username` VARCHAR(100) NOT NULL , `highscore` INT NOT NULL)"
	__sql_create_table = 	"""CREATE TABLE IF NOT EXISTS "user" (
	"id"	INTEGER UNIQUE,
	"username"	VARCHAR(100) NOT NULL,
	"highscore"	INT NOT NULL,
	"lastlogin"	TEXT,
	"played_time"	INTEGER,
	PRIMARY KEY("id")
);"""

	__sqlhandle = 0 #Statichandle

	def __init__(self) -> None:
		
		print("Userklasse erstellt")
		
		if(len(self.__username) <= 0 or self.__user == "") and (self.__uid == -1):
			#print("Es existieren noch keine Daten!")

			if(self.__sqlhandle == 0):
				self.__sqlhandle = sqlite3.connect("user.db")
				cursor = self.__sqlhandle.cursor()
				cursor.execute(self.__sql_create_table)
				self.__sqlhandle.commit()

	def __del__(self):
		print("Userklasse zerstört")
		if(self.__sqlhandle != 0):
			print(self.__sqlhandle)
			print("Datenbank wird ordentlich geschlossen\n")
			self.__sqlhandle.close()
			#self.__sqlhandle = 0
			#print(self.__sqlhandle) Debug only
		

	def createuser(self, username :str):
		if(len(username) > 0):
			cursor = self.__sqlhandle.cursor()
			if(cursor != 0):
				if(self.__username == ""):
					print("SQLHANDLE:", self.__sqlhandle)
					sql = "INSERT INTO user (username, highscore, lastlogin) VALUES('"+username+"', 0, datetime())"
					try:
						cursor.execute(sql)
						self.__sqlhandle.commit()
						print("User hinzugefügt!")
					except:
						print("Es ist beim Erstellen es Spielers ein Fehler aufgetreten!")
			else:
				print("Scheinbar besteht keine Verbindung zur Datenbank")
		else:
			print("Es wurde kein Name übergeben")


	def select(self, username):
		sql = "SELECT * FROM user WHERE username ='"+username+"'"
		sql_update_login_date = "UPDATE user SET lastlogin = datetime() WHERE username = '"+username+"'"
		try:
			c = self.__sqlhandle.cursor()
			row = c.execute(sql)
			res = row.fetchone()
			c.execute(sql_update_login_date)
			self.__sqlhandle.commit()
			self.__uid = res[0]
			self.__username = res[1]
			self.__highscore = res[2]
			self.__lastlogin = res[3]
			
		except:
			print("Fehler bei der Nutzerauswahl")
			return False
			
		return True
	
	def update_user_highscore(self, score:int):
		"""Updates users highscore"""
		sql = "SELECT * FROM user WHERE username ='"+self.getusername()+"'"
		sql_update_highscore = "UPDATE user SET highscore = "+str(score)+" WHERE username = '"+self.getusername()+"'"
		try:
			c = self.__sqlhandle.cursor()
			row = c.execute(sql)
			res = row.fetchone()
			c.execute(sql_update_highscore)
			self.__sqlhandle.commit()
			self.__uid = res[0]
			self.__username = res[1]
			self.__highscore = res[2]
			self.__lastlogin = res[3]
			
		except:
			print("Fehler beim Update des Highscores")
			return False
		return True
	
	def getplayed_time(self):
		return self.__played_time
	
	def getlastlogin(self):
		return self.__lastlogin

	def getusername(self):
		return str(self.__username)

	
	def gethighscore(self):
		return self.__highscore

	def getuid(self):
		return self.__uid

	def listallusers(self):
		cursor = self.__sqlhandle.cursor()

		for row in cursor.execute("SELECT * FROM user"):
			print("ID:",row[0],", Username:", row[1], ", Highscore:", row[2])
			self.__all_listed_users.append(row[1])
			print (self.__all_listed_users)

		cursor.close()
		self.__sqlhandle.commit()

		return self.__all_listed_users

	def checkuserdb(self):
		"""Checks for existing user, else return false"""
		cursor = self.__sqlhandle.cursor()
		rows=cursor.execute("SELECT * FROM user")
		rows_count =len(list(rows))
		if(rows_count >= 1):
			#print("Es gibt", rows_count, "Datensätze")
			return True
		else:
			return False