# Copyright (C) 2026 BoundWare LLC. All rights reserved.
# SnacTrac is licensed under the Apache License, Version 2.0
# See Licenses/LICENSE.txt for details.


import sqlite3
from convert_money import *
from get_value_table import *


# Add new notification to database.
def append_notifications(username, priority, message):

    conn = sqlite3.connect(database="Data/Database.db")

    cur = conn.cursor()

    if priority == 0:

        cur.execute(
            """
            DELETE FROM Notifications 
            WHERE "Username" = ? AND "Priority" IN (0, 1)
            """,
            (username,),
        )

        cur.execute(
            """
            INSERT INTO Notifications ("Username", "Priority", "Message")
            VALUES (?, ?, ?)
            """,
            (
                username,
                priority,
                f"Your balance has been set to {convert_money(message)}.",
            ),
        )

    elif priority == 1:

        cur.execute(
            """
            SELECT COUNT(*) FROM Notifications 
            WHERE "Username" = ? AND "Priority" = 1
            """,
            (username,),
        )

        count = cur.fetchone()[0]

        if count > 0:

            cur.execute(
                """
                DELETE FROM Notifications 
                WHERE "Username" = ? AND "Priority" IN (0, 1)
                """,
                (username,),
            )

            cur.execute(
                """
                INSERT INTO Notifications ("Username", "Priority", "Message")
                VALUES (?, 0, ?)
                """,
                (
                    username,
                    f"Your balance has been set to {convert_money(get_value_table("Users", "Username", username, "Balance"))}.",
                ),
            )

        else:

            cur.execute(
                """
                INSERT INTO Notifications ("Username", "Priority", "Message")
                VALUES (?, 1, ?)
                """,
                (
                    username,
                    f"{convert_money(message)} has been added to your balance.",
                ),
            )

    else:

        cur.execute(
            """
            INSERT INTO Notifications ("Username", "Priority", "Message")
            VALUES (?, ?, ?)
            """,
            (
                username,
                priority,
                message,
            ),
        )

    conn.commit()

    cur.close()

    conn.close()
