# ========================================================================
# Easy User Library
#

from api.core.EasySQL import EasySQL
from datetime import datetime, timedelta
import json

sql_connection = EasySQL()


class EasyUser:

    def __init__(self):
        pass

    # Checks a users session hash along with its expiration time
    # Returns the username if valid, False if not
    #
    def authenticate_session(self, session_hash):
        sql_connection.db_init()
        sql_connection.db_connect()

        sql_result = sql_connection.select('sessions', [], {'session_id' : session_hash})

        if (len(sql_result) == 0):
            return False

        if (len(sql_result) > 1):
            return False

        # Check Time
        username = sql_result[0]['username']
        expiration_time = sql_result[0]['expires_at']
        now = datetime.now()

        if expiration_time > now:

            # Update expiration time
            future_time = datetime.now() + timedelta(minutes=30)
            sql_result = sql_connection.update('sessions', {'expires_at' : future_time.strftime('%Y-%m-%d %H:%M:%S')}, {'session_id': session_hash})

            return username

        else:
            sql_connection.delete('sessions', {'session_id' : session_hash})

        return False



    # Gets all attributes of a user as a dictionary
    #
    def get_attributes(self, username):
        sql_connection.db_init()
        sql_connection.db_connect()

        try:
            sql_result = sql_connection.select('users', [], {'username': username})

            if not sql_result:
                return {}  # No user found

            user_row = sql_result[0]
            attributes_json = user_row.get('attributes', '{}')

            # Ensure it's a string and load it
            if not isinstance(attributes_json, str):
                return {}

            attributes = json.loads(attributes_json)
            if not isinstance(attributes, dict):
                return {}

            return attributes

        except (json.JSONDecodeError, KeyError, IndexError, TypeError) as e:
            # Log error or print if needed: print(f"Attribute load error: {e}")
            return {}



    # Sets all attributes of a user as a dictionary
    #
    def set_attributes(self, username, attributes):
        sql_connection.db_init()
        sql_connection.db_connect()

        # Ensure we're working with a dict
        if not isinstance(attributes, dict):
            # Optionally log or raise an error
            return False

        try:
            attributes_json = json.dumps(attributes)

            # You can optionally check if user exists first
            sql_result = sql_connection.select('users', ['id'], {'username': username})
            if not sql_result:
                return False  # User not found

            # Update the attributes column
            update_result = sql_connection.update(
                'users',
                {'attributes': attributes_json},
                {'username': username}
            )

            return True  # True or success indicator

        except (TypeError, ValueError) as e:
            # Log error or print if needed: print(f"Attribute set error: {e}")
            return False
