import socket
import threading
import os
import json
import database
from dotenv import load_dotenv

load_dotenv()

# retrieves host data from environment
HOST = os.getenv("HOST")
PORT = os.getenv("PORT")
db = database.Database(os.getenv("DBNAME"), os.getenv("DBHOST"), os.getenv("DBUSER"), os.getenv("DBPASSWORD"), os.getenv("DBPORT"))

sessions = {}

# TODO: setup tcp service for authorization
def handle_connection(socket:socket, address):
    # states that a connection has been established
    print(f"Connected with {address}")

    # Communication with client
    while True:
        data = socket.recv(1024)
        if not data:
            break

        # decode message for handling
        message = data.decode()
        message_json = json.loads(message)
        print(f"received message from {address}: {message}")

        # decide which event should be performed
        if message_json["event"]  == "login":

            username = message_json["username"]
            password = message_json["password"]

            # encode message and respond to client
            # TODO: request user data
            db.fetchone(f"SELECT * FROM users WHERE username={username} AND password={password}")
            # TODO: validate user data
            # TODO: create session
            # TODO: return session to client
            response = f"<place_holder_message>"
            socket.sendall(response.encode())
        elif message_json["event"]  == "register":
            # encode message and respond to client
            # TODO: connect to databasse
            # TODO: request user data
            # TODO: validate user data
            # TODO: create session
            # TODO: return session to client
            response = f"<place_holder_message>"
            socket.sendall(response.encode())
        elif message_json["event"]  == "logout":
            # encode message and respond to client
            # TODO: connect to databasse
            # TODO: request user data
            # TODO: validate user data
            # TODO: create session
            # TODO: return session to client
            response = f"<place_holder_message>"
            socket.sendall(response.encode())
        elif message_json["event"]  == "sessionrefresh":
            # encode message and respond to client
            # TODO: connect to databasse
            # TODO: request user data
            # TODO: validate user data
            # TODO: create session
            # TODO: return session to client
            response = f"<place_holder_message>"
            socket.sendall(response.encode())

    # connection is not required anymore and gets closed
    socket.close()
    print(f"connection closed for {address}")

# create tcp socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# make socket bind connection info and listen for connections
socket.bind(HOST, PORT)
socket.listen()
print(f"authorization server online on {HOST}:{PORT}")

# server loop forwards connection to handle_connection
while True:
    # accept incomming connection
    # TODO: validate this connection is a valid game connection
    client_socket, client_address = server_socket.accept()

    # create network thread for connection
    client_thread = threading.Thread(target=handle_connection, args=(client_socket, client_address))
    client_thread.start()