# 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 PySimpleGUI as sg
from append_history import *
from asset_image_icon_snactrac import *
from asset_image_preview_no_image import *
from asset_image_preview_no_selection import *
from clean_items_store import *
from clear_events import *
from convert_money import *
from delete_entry_table import *
from format_items_store import *
from get_data_table import *
from get_notifications import *
from get_value_table import *
from get_version import *
from move_window_center import *
from play_sound import *
from set_value_table import *
from window_popup_general import *
from window_popup_purchase import *


# Handle store window interaction.
def window_store(username, mode):

    timeout = 0

    selection = None

    query = ""

    data_items = clean_items_store(get_data_table("Items"))

    data_items_filtered = data_items

    if mode == "user":

        ask_log_out = get_value_table(
            table="Users",
            column="Username",
            identifier=username,
            property="Ask Log Out",
        )

    element_buttons = [
        sg.Push(),
        sg.Button(
            button_text="Log Out [ESC]",
            font=("Roboto", 13, "bold"),
            key="-BUTTON_LOG_OUT-",
        ),
        sg.Button(
            button_text="Mode [TAB]",
            font=("Roboto", 13, "bold"),
            key="-BUTTON_MODE-",
        ),
        sg.Button(
            button_text="Purchase [ENTER]",
            font=("Roboto", 13, "bold"),
            key="-BUTTON_PURCHASE-",
        ),
        sg.Push(),
    ]

    if mode == "guest":

        greeting = "Welcome, Guest!"

        search = "Name"

        search_color = "#469cb9"

        money_header = "Due:"

        money = 0.0

        money_color = "grey28"

    else:

        if mode == "user":

            name = (
                get_value_table(
                    table="Users",
                    column="Username",
                    identifier=username,
                    property="First Name",
                ),
                get_value_table(
                    table="Users",
                    column="Username",
                    identifier=username,
                    property="Last Name",
                ),
            )

            greeting = "Welcome, %s %s!" % (name)

            element_buttons.insert(
                2,
                sg.Button(
                    button_text="Profile [END]",
                    font=("Roboto", 13, "bold"),
                    key="-BUTTON_PROFILE-",
                ),
            )

        elif mode == "admin":

            name = (
                get_value_table(
                    table="Users",
                    column="Username",
                    identifier=username,
                    property="First Name",
                ),
                get_value_table(
                    table="Users",
                    column="Username",
                    identifier=username,
                    property="Last Name",
                ),
            )

            greeting = "Welcome, %s %s! (Admin)" % (name)

        search = get_value_table("Users", "Username", username, "Search Mode")

        if search == "Name":

            search_color = "#469cb9"

        elif search == "ID":

            search_color = "#b96346"

        elif search == "Barcode":

            search_color = "#6346b9"

        money_header = "Balance:"

        money = get_value_table("Users", "Username", username, "Balance")

        if money < 0:

            money_color = "#b94646"

        elif money > 0:

            money_color = "#65b946"

        else:

            money_color = "grey28"

    layout = [
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 20),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Text(
                text="STORE",
                font=("Roboto", 19, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Push(),
            sg.Text(
                text=greeting,
                font=("Roboto", 12, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 16),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(14, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title="Selection:",
                title_location="n",
                border_width=0,
                layout=[
                    [
                        sg.Input(
                            default_text="None",
                            size=(16, 1),
                            justification="center",
                            background_color="grey28",
                            text_color="white",
                            font=("Roboto", 12, "bold"),
                            enable_events=True,
                            key="-INPUT_SELECTION-",
                            pad=(0, 0),
                            selected_text_color="black",
                        ),
                    ]
                ],
                size=(454, 109),
                font=("Roboto", 8),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(24, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title="Mode:",
                title_location="n",
                border_width=0,
                layout=[
                    [
                        sg.Input(
                            default_text=search,
                            size=(16, 1),
                            justification="center",
                            background_color=search_color,
                            text_color="white",
                            font=("Roboto", 12, "bold"),
                            enable_events=True,
                            key="-INPUT_MODE-",
                            pad=(0, 0),
                            selected_text_color="black",
                        ),
                    ]
                ],
                size=(454, 109),
                font=("Roboto", 8),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(24, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title="Search:",
                title_location="n",
                border_width=0,
                layout=[
                    [
                        sg.Input(
                            size=(15, 1),
                            justification="center",
                            font=("Roboto", 12),
                            enable_events=True,
                            key="-INPUT_SEARCH-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(401, 109),
                font=("Roboto", 8),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(24, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=money_header,
                title_location="n",
                border_width=0,
                layout=[
                    [
                        sg.Input(
                            default_text=convert_money(money),
                            size=(16, 1),
                            justification="center",
                            background_color=money_color,
                            text_color="white",
                            font=("Roboto", 12, "bold"),
                            enable_events=True,
                            key="-INPUT_MONEY-",
                            pad=(0, 0),
                            selected_text_color="black",
                        ),
                    ]
                ],
                size=(454, 109),
                font=("Roboto", 8),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 23),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(14, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Frame(
                            title=None,
                            layout=[
                                [
                                    sg.Image(
                                        source=preview_no_selection,
                                        key="-IMAGE_ITEM-",
                                        size=(406, 406),
                                        pad=(0, 0),
                                        enable_events=True,
                                    )
                                ]
                            ],
                            background_color="#283B5B",
                            relief="sunken",
                            size=(408, 408),
                            pad=(22, 22),
                            border_width=1,
                        ),
                    ]
                ],
                background_color="#283B5B",
                relief="raised",
                size=(454, 454),
                pad=(0, 0),
                border_width=1,
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(24, 0),
                pad=(0, 0),
            ),
            sg.Table(
                values=format_items_store(data_items_filtered),
                headings=["ID", "Name", "Price", "Stock"],
                col_widths=[9, 40, 9, 9],
                auto_size_columns=False,
                select_mode="browse",
                display_row_numbers=False,
                num_rows=9,
                font=("Roboto Mono", 8),
                justification="center",
                alternating_row_color="#465974",
                enable_events=True,
                pad=(0, 0),
                key="-TABLE_ITEMS-",
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 21),
                pad=(0, 0),
            ),
        ],
        [
            *element_buttons,
        ],
    ]

    window = sg.Window(
        title="SnacTrac %s - Store" % get_version(),
        size=(1883, 954),
        layout=layout,
        finalize=True,
        modal=True,
        enable_close_attempted_event=True,
        icon=icon_snactrac,
    )

    while True:

        event, values = window.read(timeout)

        if timeout == None and (
            event == "-BUTTON_LOG_OUT-" or event == sg.WIN_CLOSE_ATTEMPTED_EVENT
        ):

            play_sound("tick")

            if mode == "guest":

                if money > 0:

                    if window_popup_general(
                        title="Confirm Deposit",
                        icon="choice",
                        text="I have deposited %s to the vendor."
                        % convert_money(money),
                        button_false="Cancel",
                        button_true="Confirm",
                    ):

                        money = 0.0

                        money_color = "grey28"

                        window["-INPUT_MONEY-"].update(
                            value=convert_money(money), background_color=money_color
                        )

                        window_popup_general(
                            title="Confirm Log Out",
                            icon="exit",
                            text="You will now be logged out.",
                            button_true="Okay",
                        )

                        window.close()

                        return "welcome", None, "user"

                else:

                    if window_popup_general(
                        title="Confirm Log Out",
                        icon="exit",
                        text="Are you sure you want to log out?",
                        button_false="Cancel",
                        button_true="Confirm",
                    ):

                        window.close()

                        return "welcome", None, "user"

            elif mode == "user":

                if ask_log_out:

                    if window_popup_general(
                        title="Confirm Log Out",
                        icon="exit",
                        text="Are you sure you want to log out?",
                        button_false="Cancel",
                        button_true="Confirm",
                    ):

                        window.close()

                        set_value_table(
                            "Users",
                            "Username",
                            username,
                            "Search Mode",
                            values["-INPUT_MODE-"],
                        )

                        return "welcome", None, "user"

                else:

                    window.close()

                    set_value_table(
                        "Users",
                        "Username",
                        username,
                        "Search Mode",
                        values["-INPUT_MODE-"],
                    )

                    return "welcome", None, "user"

            elif mode == "admin":

                window.close()

                return "users", None, "user"

        if timeout == None and event == "-INPUT_SELECTION-":

            if selection:

                window["-INPUT_SELECTION-"].update(" %s " % selection[1])

            else:

                window["-INPUT_SELECTION-"].update("None")

            window["-INPUT_SEARCH-"].set_focus()

        if timeout == None and event == "-INPUT_MODE-":

            window["-INPUT_MODE-"].update(search)

            window["-INPUT_SEARCH-"].set_focus()

        if timeout == None and event == "-INPUT_SEARCH-":

            if query != values["-INPUT_SEARCH-"].replace(" ", ""):

                query = values["-INPUT_SEARCH-"].replace(" ", "")

                if search == "Name":

                    data_items_filtered = [
                        item
                        for item in data_items
                        if query.lower() in item[1].lower().replace(" ", "")
                    ]

                    window["-TABLE_ITEMS-"].update(
                        format_items_store(data_items_filtered)
                    )

                    if len(data_items_filtered) == 1:

                        window["-TABLE_ITEMS-"].update(select_rows=[0])

                elif search == "ID":

                    if query.isdigit():

                        for i, item in enumerate(data_items_filtered):

                            if item[0] == int(query):

                                window["-TABLE_ITEMS-"].update(select_rows=[i])

                                window["-TABLE_ITEMS-"].Widget.yview_moveto(
                                    i / len(data_items_filtered)
                                )

                                break

                            else:

                                window["-TABLE_ITEMS-"].update(select_rows=[])

                    else:

                        window["-TABLE_ITEMS-"].update(select_rows=[])

                        window["-TABLE_ITEMS-"].Widget.yview_moveto(0)

                elif search == "Barcode":

                    for i, item in enumerate(data_items_filtered):

                        if item[4] == query:

                            window["-TABLE_ITEMS-"].update(select_rows=[i])

                            window["-TABLE_ITEMS-"].Widget.yview_moveto(
                                i / len(data_items_filtered)
                            )

                            break

                        else:

                            window["-TABLE_ITEMS-"].update(select_rows=[])

                            window["-TABLE_ITEMS-"].Widget.yview_moveto(0)

        if timeout == None and event == "-INPUT_MONEY-":

            window["-INPUT_MONEY-"].update(convert_money(money))

            window["-INPUT_SEARCH-"].set_focus()

        if timeout == None and event == "-TABLE_ITEMS-":

            if values["-TABLE_ITEMS-"]:

                if selection != data_items_filtered[values["-TABLE_ITEMS-"][0]]:

                    play_sound("click")

                    selection = data_items_filtered[values["-TABLE_ITEMS-"][0]]

                    window["-INPUT_SELECTION-"].update(
                        value=" %s " % selection[1], background_color="#65b946"
                    )

                    image = get_value_table("Items", "ID", selection[0], "Image")

                    if image:

                        window["-IMAGE_ITEM-"].update(image)

                    else:

                        window["-IMAGE_ITEM-"].update(preview_no_image)

                else:

                    play_sound("nope")

                clear_events(window)

            else:

                play_sound("scrape")

                selection = None

                window["-INPUT_SELECTION-"].update(
                    value="None", background_color="grey28"
                )

                window["-IMAGE_ITEM-"].update(preview_no_selection)

            window["-INPUT_SEARCH-"].set_focus()

        if timeout == None and event == "-BUTTON_PROFILE-":

            play_sound("tick")

            window.close()

            set_value_table(
                "Users",
                "Username",
                username,
                "Search Mode",
                values["-INPUT_MODE-"],
            )

            return "profile", username, mode

        if timeout == None and event == "-BUTTON_MODE-":

            play_sound("tick")

            if search == "Name":

                search = "ID"

                window["-INPUT_MODE-"].update(value=search, background_color="#b96346")

            elif search == "ID":

                search = "Barcode"

                window["-INPUT_MODE-"].update(value=search, background_color="#6346b9")

            else:

                search = "Name"

                window["-INPUT_MODE-"].update(value=search, background_color="#469cb9")

            selection = None

            window["-INPUT_SELECTION-"].update(value="None", background_color="grey28")

            query = ""

            window["-INPUT_SEARCH-"].update(query)

            window["-INPUT_SEARCH-"].set_focus()

            data_items_filtered = data_items

            window["-TABLE_ITEMS-"].update(format_items_store(data_items_filtered))

            window["-TABLE_ITEMS-"].Widget.yview_moveto(0)

        if timeout == None and event == "-BUTTON_PURCHASE-":

            play_sound("tick")

            if selection and selection[3] > 0:

                quantity = window_popup_purchase(
                    name=selection[1],
                    stock=selection[3],
                    price=selection[2],
                )

                if quantity:

                    set_value_table(
                        table="Items",
                        column="ID",
                        identifier=selection[0],
                        property="Stock",
                        value=selection[3] - quantity,
                    )

                    if mode == "guest":

                        money += selection[2] * quantity

                        if money > 0:

                            money_color = "#b94646"

                        else:

                            money_color = "grey28"

                        append_history(
                            mode="Guest",
                            action="Purchase",
                            description='%s x "%s" for %s each'
                            % (
                                quantity,
                                selection[1],
                                convert_money(selection[2]),
                            ),
                            total=selection[2] * quantity,
                            balance_old=None,
                            balance_new=None,
                            stock_old=selection[3],
                            stock_new=selection[3] - quantity,
                            profit=selection[5] * quantity,
                        )

                    else:

                        money -= selection[2] * quantity

                        if money < 0:

                            money_color = "#b94646"

                        elif money > 0:

                            money_color = "#65b946"

                        else:

                            money_color = "grey28"

                        set_value_table(
                            table="Users",
                            column="Username",
                            identifier=username,
                            property="Balance",
                            value=money,
                        )

                        append_history(
                            user="%s %s (%s)"
                            % (
                                name[0],
                                name[1],
                                username,
                            ),
                            mode=mode.capitalize(),
                            action="Purchase",
                            description='%s x "%s" for %s each'
                            % (
                                quantity,
                                selection[1],
                                convert_money(selection[2]),
                            ),
                            total=selection[2] * quantity,
                            balance_old=money + selection[2] * quantity,
                            balance_new=money,
                            stock_old=selection[3],
                            stock_new=selection[3] - quantity,
                            profit=selection[5] * quantity,
                        )

                    window["-INPUT_SELECTION-"].update(
                        value="None", background_color="grey28"
                    )

                    query = ""

                    window["-INPUT_SEARCH-"].update(query)

                    window["-INPUT_SEARCH-"].set_focus()

                    window["-INPUT_MONEY-"].update(
                        value=convert_money(money), background_color=money_color
                    )

                    window["-IMAGE_ITEM-"].update(preview_no_selection)

                    data_items = clean_items_store(get_data_table("Items"))

                    data_items_filtered = data_items

                    window["-TABLE_ITEMS-"].update(
                        format_items_store(data_items_filtered)
                    )

                    window["-TABLE_ITEMS-"].Widget.yview_moveto(0)

                    window_popup_general(
                        title="Purchase Complete",
                        icon="success",
                        text='You purchased %s x "%s" for %s.'
                        % (
                            quantity,
                            selection[1],
                            convert_money(selection[2] * quantity),
                        ),
                        button_true="Okay",
                        sound="chaching",
                    )

                    selection = None

                    clear_events(window)

            elif selection:

                window_popup_general(
                    title="Insufficient Stock",
                    text="This item is currently out of stock.",
                    button_true="Okay",
                )

            else:

                window_popup_general(
                    title="Missing Selection",
                    text="An item must be selected to purchase.",
                    button_true="Okay",
                )

        if timeout == 0:

            window.bind("<Escape>", "-BUTTON_LOG_OUT-")

            if mode == "user":

                window.bind("<End>", "-BUTTON_PROFILE-")

            window.bind("<Tab>", "-BUTTON_MODE-")

            window.bind("<Return>", "-BUTTON_PURCHASE-")

            window["-INPUT_SEARCH-"].set_focus()

            move_window_center(window)

            timeout = None

            play_sound("pop")

            if mode == "user":

                data_notifications = get_notifications(username)

                if data_notifications:

                    for notification in data_notifications:

                        window_popup_general(
                            title="User Notification",
                            icon="success",
                            text=notification[3],
                            button_true="Okay",
                        )

                        delete_entry_table("Notifications", "ID", notification[0])
