# 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 io
import os
import PySimpleGUI as sg
import re
import sqlite3
from PIL import Image
from append_items import *
from append_triggers import *
from asset_image_icon_snactrac import *
from asset_image_preview_no_image import *
from asset_image_preview_no_selection import *
from clean_items import *
from clear_events import *
from delete_entry_table import *
from format_items_admin import *
from get_value_table import *
from get_version import *
from get_data_table import *
from move_window_center import *
from play_sound import *
from set_value_table import *
from window_popup_general import *


# Handle items window interaction.
def window_items():

    timeout = 0

    triggers = []

    selection = None

    query = ""

    properties = [
        "ID",
        "Name",
        "Price",
        "Profit",
        "Stock",
        "Barcode",
        "Image",
    ]

    property = properties[0]

    data_items = clean_items(get_data_table("Items"))

    data_items_filtered = data_items

    layout = [
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 20),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Text(text="ITEMS", font=("Roboto", 19, "bold"), pad=(0, 0)),
            sg.Push(),
        ],
        [
            sg.Push(),
            sg.Text(
                text="Select an item to manage, or change image.",
                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:",
                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",
                        ),
                    ],
                ],
                title_location="n",
                size=(454, 109),
                font=("Roboto", 8),
                pad=(0, 0),
                border_width=0,
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(24, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title="Search:",
                layout=[
                    [
                        sg.Input(
                            size=(17, 1),
                            justification="center",
                            font=("Roboto", 12),
                            enable_events=True,
                            key="-INPUT_SEARCH-",
                            pad=(0, 0),
                        ),
                    ],
                ],
                title_location="n",
                size=(454, 109),
                font=("Roboto", 8),
                pad=(0, 0),
                border_width=0,
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(24, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title="Property:",
                layout=[
                    [
                        sg.Combo(
                            values=properties,
                            default_value=properties[0],
                            size=(15, 1),
                            enable_events=True,
                            key="-COMBO_PROPERTY-",
                            pad=(0, 0),
                            expand_x=False,
                            readonly=True,
                            font=("Roboto", 12),
                        ),
                    ],
                ],
                title_location="n",
                size=(426, 109),
                font=("Roboto", 8),
                pad=(0, 0),
                border_width=0,
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(24, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title="Value:",
                layout=[
                    [
                        sg.Input(
                            size=(17, 1),
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_VALUE-",
                            pad=(0, 0),
                        ),
                        sg.Button(
                            button_text="Modify",
                            font=("Roboto", 12, "bold"),
                            size=(454, 65),
                            visible=False,
                            pad=(0, 0),
                            key="-BUTTON_IMAGE-",
                        ),
                    ],
                ],
                title_location="n",
                size=(454, 109),
                font=("Roboto", 8),
                pad=(0, 0),
                border_width=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),
                                    )
                                ]
                            ],
                            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.Frame(
                title=None,
                layout=[
                    [
                        sg.Table(
                            values=format_items_admin(data_items),
                            headings=properties[:6],
                            col_widths=[9, 42, 9, 9, 9, 27],
                            auto_size_columns=False,
                            select_mode="browse",
                            display_row_numbers=False,
                            num_rows=16,
                            font=("Roboto Mono", 5),
                            justification="center",
                            alternating_row_color="#465974",
                            enable_events=True,
                            pad=(0, 0),
                            key="-TABLE_ITEMS-",
                        ),
                    ],
                ],
                size=(1384, 454),
                pad=(0, 0),
                border_width=0,
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 21),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Button(
                button_text="Go Back [ESC]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_GO_BACK-",
            ),
            sg.Button(
                button_text="New [END]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_NEW-",
            ),
            sg.Button(
                button_text="Delete [DEL]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_DELETE-",
            ),
            sg.Button(
                button_text="Save [ENTER]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_SAVE-",
            ),
            sg.Push(),
        ],
        [
            sg.FileBrowse(
                file_types=(("Image Files", "*.png;*.jpg"),),
                initial_folder=os.path.join(os.path.expanduser("~"), "Downloads"),
                enable_events=True,
                key="-FILE_BROWSE_IMAGE-",
                visible=False,
            ),
        ],
    ]

    window = sg.Window(
        title="SnacTrac %s - Items" % get_version(),
        size=(1908, 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_GO_BACK-" or event == sg.WIN_CLOSE_ATTEMPTED_EVENT
        ):

            play_sound("tick")

            window.close()

            return "admin"

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

            if selection:

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

            else:

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

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

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

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

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

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

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

                if len(data_items_filtered) == 1:

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

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

            if property != values["-COMBO_PROPERTY-"]:

                play_sound("tick")

                property = values["-COMBO_PROPERTY-"]

            else:

                play_sound("nope")

            if values["-COMBO_PROPERTY-"] == "Image":

                window["-INPUT_VALUE-"].update(visible=False)

                window["-BUTTON_IMAGE-"].update(visible=True)

            else:

                window["-BUTTON_IMAGE-"].update(visible=False)

                window["-INPUT_VALUE-"].update(visible=True)

            window["-INPUT_VALUE-"].update("")

            if selection:

                if values["-COMBO_PROPERTY-"] == "ID":

                    window["-INPUT_VALUE-"].update(selection[0])

                elif values["-COMBO_PROPERTY-"] == "Name":

                    window["-INPUT_VALUE-"].update(selection[1])

                elif values["-COMBO_PROPERTY-"] == "Price":

                    window["-INPUT_VALUE-"].update(convert_money(selection[2]))

                elif values["-COMBO_PROPERTY-"] == "Profit":

                    window["-INPUT_VALUE-"].update(convert_money(selection[3]))

                elif values["-COMBO_PROPERTY-"] == "Stock":

                    window["-INPUT_VALUE-"].update(selection[4])

                elif values["-COMBO_PROPERTY-"] == "Barcode":

                    if selection[5]:

                        window["-INPUT_VALUE-"].update(selection[5])

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

            window["-COMBO_PROPERTY-"].Widget.select_range(0, 0)

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

            play_sound("tick")

            if selection:

                if get_value_table("Items", "ID", selection[0], "Image"):

                    response = window_popup_general(
                        title="Confirm Change Image",
                        icon="choice",
                        text="How do you want to modify the selected item's image?",
                        button_false="Cancel",
                        button_none="Delete Image",
                        button_true="Change Image",
                    )

                    if response == False:

                        pass

                    elif response == None:

                        set_value_table("Items", "ID", selection[0], "Image", None)

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

                        window_popup_general(
                            title="Item Property Set",
                            text="The selected item's image has been removed.",
                            button_true="Okay",
                        )

                    elif response == True:

                        window["-FILE_BROWSE_IMAGE-"].click()

                else:

                    if window_popup_general(
                        title="Confirm Change Image",
                        icon="choice",
                        text="Assign image to selected item?",
                        button_false="Cancel",
                        button_true="Confirm",
                    ):

                        window["-FILE_BROWSE_IMAGE-"].click()

            else:

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

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

            path = values["-FILE_BROWSE_IMAGE-"]

            try:

                with Image.open(path) as image:

                    image = image.convert("RGB").resize((406, 406))

                    image_bytes = io.BytesIO()

                    image.save(image_bytes, format="PNG")

                    image = image_bytes.getvalue()

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

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

                    window_popup_general(
                        title="Item Property Set",
                        text="The selected item's image has been set.",
                        button_true="Okay",
                    )

            except:

                window_popup_general(
                    title="Invalid Input",
                    text="The image selected is not valid.",
                    button_true="Okay",
                )

        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=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["-INPUT_VALUE-"].update("")

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

            if selection:

                if values["-COMBO_PROPERTY-"] == "ID":

                    window["-INPUT_VALUE-"].update(selection[0])

                elif values["-COMBO_PROPERTY-"] == "Name":

                    window["-INPUT_VALUE-"].update(selection[1])

                elif values["-COMBO_PROPERTY-"] == "Price":

                    window["-INPUT_VALUE-"].update(convert_money(selection[2]))

                elif values["-COMBO_PROPERTY-"] == "Profit":

                    window["-INPUT_VALUE-"].update(convert_money(selection[3]))

                elif values["-COMBO_PROPERTY-"] == "Stock":

                    window["-INPUT_VALUE-"].update(selection[4])

                elif values["-COMBO_PROPERTY-"] == "Barcode":

                    if selection[5]:

                        window["-INPUT_VALUE-"].update(selection[5])

                    else:

                        window["-INPUT_VALUE-"].update("")

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

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

            play_sound("tick")

            if window_popup_general(
                title="Confirm Add Item",
                text="Add a new item?",
                button_true="Confirm",
                button_false="Cancel",
            ):

                query = ""

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

                append_items()

                selection = None

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

                window["-INPUT_VALUE-"].update("")

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

                data_items = clean_items(get_data_table("Items"))

                data_items_filtered = data_items

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

                clear_events(window)

                window_popup_general(
                    title="Item Added",
                    icon="success",
                    text="A new item has been added.",
                    button_true="Okay",
                )

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

            play_sound("tick")

            if selection:

                if window_popup_general(
                    title="Confirm Delete Item",
                    text="Delete the selected item?",
                    button_true="Confirm",
                    button_false="Cancel",
                ):

                    query = ""

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

                    delete_entry_table("Items", "ID", selection[0])

                    selection = None

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

                    window["-INPUT_VALUE-"].update("")

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

                    data_items = clean_items(get_data_table("Items"))

                    data_items_filtered = data_items

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

                    clear_events(window)

                    window_popup_general(
                        title="Item Deleted",
                        icon="success",
                        text="The selected item has been deleted.",
                        button_true="Okay",
                    )

            else:

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

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

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

            play_sound("tick")

            if selection:

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

                if values["-COMBO_PROPERTY-"] == "ID":

                    try:

                        value = int(values["-INPUT_VALUE-"])

                        if selection[0] == value:

                            window["-INPUT_VALUE-"].update(selection[0])

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-ID_SAME-")

                        elif value < 1:

                            window["-INPUT_VALUE-"].update(selection[0])

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-ID_LOW-")

                        else:

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

                            cur = conn.cursor()

                            cur.execute(
                                "SELECT EXISTS(SELECT 1 FROM Items WHERE ID = ?)",
                                (value,),
                            )

                            if cur.fetchone()[0]:

                                window["-INPUT_VALUE-"].update(selection[0])

                                window["-INPUT_VALUE-"].Widget.select_range(
                                    0, sg.tk.END
                                )

                                append_triggers(triggers, "-ID_TAKEN-")

                            else:

                                if window_popup_general(
                                    title="Confirm Item Property",
                                    icon="choice",
                                    text='Set the selected item\'s id to "%s"?' % value,
                                    button_false="Cancel",
                                    button_true="Confirm",
                                ):

                                    set_value_table(
                                        "Items",
                                        "ID",
                                        selection[0],
                                        "ID",
                                        value,
                                    )

                                    append_triggers(triggers, "-ID_CHANGED-")

                                else:

                                    window["-INPUT_VALUE-"].update(selection[0])

                                    window["-INPUT_VALUE-"].Widget.select_range(
                                        0, sg.tk.END
                                    )

                            cur.close()

                            conn.close()

                    except:

                        if values["-INPUT_VALUE-"].replace(" ", "") == "":

                            append_triggers(triggers, "-ID_BLANK-")

                        else:

                            append_triggers(triggers, "-ID_INVALID-")

                        window["-INPUT_VALUE-"].update(selection[0])

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                if values["-COMBO_PROPERTY-"] == "Name":

                    if selection[1] == values["-INPUT_VALUE-"]:

                        window["-INPUT_VALUE-"].update(selection[1])

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-NAME_SAME-")

                    elif values["-INPUT_VALUE-"].replace(" ", "") == "":

                        window["-INPUT_VALUE-"].update(selection[1])

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-NAME_BLANK-")

                    elif (
                        values["-INPUT_VALUE-"]
                        != re.sub(r"\s{2,}", " ", values["-INPUT_VALUE-"]).strip()
                    ):

                        window["-INPUT_VALUE-"].update(selection[1])

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-NAME_SPACE-")

                    else:

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

                        cur = conn.cursor()

                        cur.execute(
                            "SELECT EXISTS(SELECT 1 FROM Items WHERE Name = ?)",
                            (values["-INPUT_VALUE-"],),
                        )

                        if cur.fetchone()[0]:

                            window["-INPUT_VALUE-"].update(selection[1])

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-NAME_TAKEN-")

                        else:

                            if window_popup_general(
                                title="Confirm Item Property",
                                icon="choice",
                                text='Set the selected item\'s name to "%s"?'
                                % values["-INPUT_VALUE-"],
                                button_false="Cancel",
                                button_true="Confirm",
                            ):

                                set_value_table(
                                    "Items",
                                    "ID",
                                    selection[0],
                                    "Name",
                                    values["-INPUT_VALUE-"],
                                )

                                append_triggers(triggers, "-NAME_CHANGED-")

                            else:

                                window["-INPUT_VALUE-"].update(selection[1])

                                window["-INPUT_VALUE-"].Widget.select_range(
                                    0, sg.tk.END
                                )

                        cur.close()

                        conn.close()

                if values["-COMBO_PROPERTY-"] == "Price":

                    try:

                        value = convert_money(values["-INPUT_VALUE-"])

                        if selection[2] == value:

                            window["-INPUT_VALUE-"].update(convert_money(selection[2]))

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-PRICE_SAME-")

                        elif value < 0:

                            window["-INPUT_VALUE-"].update(convert_money(selection[2]))

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-PRICE_LOW-")

                        else:

                            window["-INPUT_VALUE-"].update(convert_money(value))

                            if window_popup_general(
                                title="Confirm Item Property",
                                icon="choice",
                                text="Set the selected item's price to %s?"
                                % convert_money(value),
                                button_false="Cancel",
                                button_true="Confirm",
                            ):

                                set_value_table(
                                    "Items",
                                    "ID",
                                    selection[0],
                                    "Price",
                                    value,
                                )

                                append_triggers(triggers, "-PRICE_CHANGED-")

                            else:

                                window["-INPUT_VALUE-"].update(
                                    convert_money(selection[2])
                                )

                                window["-INPUT_VALUE-"].Widget.select_range(
                                    0, sg.tk.END
                                )

                    except:

                        window["-INPUT_VALUE-"].update(convert_money(selection[2]))

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-PRICE_INVALID-")

                if values["-COMBO_PROPERTY-"] == "Profit":

                    try:

                        value = convert_money(values["-INPUT_VALUE-"])

                        if selection[3] == value:

                            window["-INPUT_VALUE-"].update(convert_money(selection[3]))

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-PROFIT_SAME-")

                        elif value < 0:

                            window["-INPUT_VALUE-"].update(convert_money(selection[3]))

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-PROFIT_LOW-")

                        else:

                            window["-INPUT_VALUE-"].update(convert_money(value))

                            if window_popup_general(
                                title="Confirm Item Property",
                                icon="choice",
                                text="Set the selected item's profit to %s?"
                                % convert_money(value),
                                button_false="Cancel",
                                button_true="Confirm",
                            ):

                                set_value_table(
                                    "Items",
                                    "ID",
                                    selection[0],
                                    "Profit",
                                    value,
                                )

                                append_triggers(triggers, "-PROFIT_CHANGED-")

                            else:

                                window["-INPUT_VALUE-"].update(
                                    convert_money(selection[3])
                                )

                                window["-INPUT_VALUE-"].Widget.select_range(
                                    0, sg.tk.END
                                )

                    except:

                        window["-INPUT_VALUE-"].update(convert_money(selection[3]))

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-PROFIT_INVALID-")

                if values["-COMBO_PROPERTY-"] == "Stock":

                    try:

                        value = int(values["-INPUT_VALUE-"])

                        if selection[4] == value:

                            window["-INPUT_VALUE-"].update(selection[4])

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-STOCK_SAME-")

                        elif value < 0:

                            window["-INPUT_VALUE-"].update(selection[4])

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-STOCK_LOW-")

                        else:

                            window["-INPUT_VALUE-"].update(value)

                            if window_popup_general(
                                title="Confirm Item Property",
                                icon="choice",
                                text="Set the selected item's stock to %s?" % value,
                                button_false="Cancel",
                                button_true="Confirm",
                            ):

                                set_value_table(
                                    "Items",
                                    "ID",
                                    selection[0],
                                    "Stock",
                                    value,
                                )

                                append_triggers(triggers, "-STOCK_CHANGED-")

                            else:

                                window["-INPUT_VALUE-"].update(selection[4])

                                window["-INPUT_VALUE-"].Widget.select_range(
                                    0, sg.tk.END
                                )

                    except:

                        window["-INPUT_VALUE-"].update(selection[4])

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-STOCK_INVALID-")

                if values["-COMBO_PROPERTY-"] == "Barcode":

                    if selection[5] == values["-INPUT_VALUE-"]:

                        if selection[5]:

                            window["-INPUT_VALUE-"].update(selection[5])

                        else:

                            window["-INPUT_VALUE-"].update("")

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-BARCODE_SAME-")

                    if selection[5] == None and values["-INPUT_VALUE-"] == "":

                        window["-INPUT_VALUE-"].update("")

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-BARCODE_BLANK-")

                    elif " " in values["-INPUT_VALUE-"]:

                        if selection[5]:

                            window["-INPUT_VALUE-"].update(selection[5])

                        else:

                            window["-INPUT_VALUE-"].update("")

                        window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                        append_triggers(triggers, "-BARCODE_SPACE-")

                    else:

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

                        cur = conn.cursor()

                        cur.execute(
                            "SELECT EXISTS(SELECT 1 FROM Items WHERE Barcode = ?)",
                            (values["-INPUT_VALUE-"],),
                        )

                        if cur.fetchone()[0]:

                            window["-INPUT_VALUE-"].update(selection[5])

                            window["-INPUT_VALUE-"].Widget.select_range(0, sg.tk.END)

                            append_triggers(triggers, "-BARCODE_TAKEN-")

                        elif values["-INPUT_VALUE-"] == "":

                            if window_popup_general(
                                title="Confirm Item Property",
                                icon="choice",
                                text="Remove the selected item's barcode?",
                                button_false="Cancel",
                                button_true="Confirm",
                            ):

                                set_value_table(
                                    "Items",
                                    "ID",
                                    selection[0],
                                    "Barcode",
                                    None,
                                )

                                append_triggers(triggers, "-BARCODE_REMOVED-")

                            else:

                                if selection[5]:

                                    window["-INPUT_VALUE-"].update(selection[5])

                                else:

                                    window["-INPUT_VALUE-"].update("")

                                window["-INPUT_VALUE-"].Widget.select_range(
                                    0, sg.tk.END
                                )

                        else:

                            if window_popup_general(
                                title="Confirm Item Property",
                                icon="choice",
                                text="Set the selected item's barcode to \"%s\"?"
                                % values["-INPUT_VALUE-"],
                                button_false="Cancel",
                                button_true="Confirm",
                            ):

                                set_value_table(
                                    "Items",
                                    "ID",
                                    selection[0],
                                    "Barcode",
                                    values["-INPUT_VALUE-"],
                                )

                                append_triggers(triggers, "-BARCODE_CHANGED-")

                            else:

                                if selection[5]:

                                    window["-INPUT_VALUE-"].update(selection[5])

                                else:

                                    window["-INPUT_VALUE-"].update("")

                                window["-INPUT_VALUE-"].Widget.select_range(
                                    0, sg.tk.END
                                )

                        cur.close()

                        conn.close()

                if values["-COMBO_PROPERTY-"] == "Image":

                    window_popup_general(
                        title="No Changes Made",
                        text="Click the value button to alter the item's image.",
                        button_true="Okay",
                    )

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

                data_items = clean_items(get_data_table("Items"))

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

                if values["-COMBO_PROPERTY-"] == "ID":

                    index = [item[1] for item in data_items_filtered].index(
                        selection[1]
                    )

                else:

                    index = [item[0] for item in data_items_filtered].index(
                        selection[0]
                    )

                selection = data_items_filtered[index]

                window["-INPUT_SELECTION-"].update(value=selection[1])

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

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

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

                clear_events(window)

            else:

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

            if triggers:

                if "-ID_SAME-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The id entered is already in use.",
                        button_true="Okay",
                    )

                if "-ID_BLANK-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The id must not be left blank.",
                        button_true="Okay",
                    )

                if "-ID_INVALID-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The id must be a whole number greater than zero.",
                        button_true="Okay",
                    )

                if "-ID_TAKEN-" in triggers:

                    window_popup_general(
                        title="ID Unavailable",
                        text="The id entered is being used by another item.",
                        button_true="Okay",
                    )

                if "-ID_LOW-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The id must be greater than zero.",
                        button_true="Okay",
                    )

                if "-NAME_SAME-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The name entered is already in use.",
                        button_true="Okay",
                    )

                if "-NAME_TAKEN-" in triggers:

                    window_popup_general(
                        title="Name Unavailable",
                        text="The name entered is being used by another item.",
                        button_true="Okay",
                    )

                if "-NAME_BLANK-" in triggers:

                    window_popup_general(
                        title="Incomplete Form",
                        text="The name must not be left blank.",
                        button_true="Okay",
                    )

                if "-NAME_SPACE-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The name must not contain excessive spaces.",
                        button_true="Okay",
                    )

                if "-ID_CHANGED-" in triggers:

                    window_popup_general(
                        title="Item Property Set",
                        icon="success",
                        text='The selected item\'s ID has been set to "%s".'
                        % values["-INPUT_VALUE-"],
                        button_true="Okay",
                    )

                if "-NAME_CHANGED-" in triggers:

                    window_popup_general(
                        title="Item Property Set",
                        icon="success",
                        text='The selected item\'s name has been set to "%s".'
                        % values["-INPUT_VALUE-"],
                        button_true="Okay",
                    )

                if "-PRICE_SAME-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The price entered is already in use.",
                        button_true="Okay",
                    )

                if "-PRICE_LOW-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The price entered must not be negative.",
                        button_true="Okay",
                    )

                if "-PRICE_INVALID-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The price entered must be a non-negative amount.",
                        button_true="Okay",
                    )

                if "-PRICE_CHANGED-" in triggers:

                    window_popup_general(
                        title="Item Property Set",
                        text="The selected item's price has been set to %s."
                        % convert_money(value),
                        button_true="Okay",
                    )

                if "-PROFIT_SAME-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The profit entered is already in use.",
                        button_true="Okay",
                    )

                if "-PROFIT_LOW-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The profit entered must not be negative.",
                        button_true="Okay",
                    )

                if "-PROFIT_INVALID-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The profit entered must be a non-negative amount.",
                        button_true="Okay",
                    )

                if "-PROFIT_CHANGED-" in triggers:

                    window_popup_general(
                        title="Item Property Set",
                        text="The selected item's stock has been set to %s."
                        % convert_money(value),
                        button_true="Okay",
                    )

                if "-STOCK_SAME-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The stock entered is already in use.",
                        button_true="Okay",
                    )

                if "-STOCK_LOW-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The stock entered must not be negative.",
                        button_true="Okay",
                    )

                if "-STOCK_INVALID-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The stock must be a non-negative whole number.",
                        button_true="Okay",
                    )

                if "-STOCK_CHANGED-" in triggers:

                    window_popup_general(
                        title="Item Property Set",
                        text="The selected item's profit has been set to %s." % value,
                        button_true="Okay",
                    )

                if "-BARCODE_SAME-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The barcode entered is already in use.",
                        button_true="Okay",
                    )

                if "-BARCODE_BLANK-" in triggers:

                    window_popup_general(
                        title="Incomplete Form",
                        text="The barcode is already empty.",
                        button_true="Okay",
                    )

                if "-BARCODE_SPACE-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The barcode must not contain excessive spaces.",
                        button_true="Okay",
                    )

                if "-BARCODE_CHANGED-" in triggers:

                    window_popup_general(
                        title="Item Property Set",
                        text="The selected item's barcode has been set to \"%s\"."
                        % values["-INPUT_VALUE-"],
                        button_true="Okay",
                    )
                
                if "-BARCODE_REMOVED-" in triggers:

                    window_popup_general(
                        title="Item Property Set",
                        text="The selected item's barcode has been removed.",
                        button_true="Okay",
                    )
                
            triggers.clear()

        if timeout == 0:

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

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

            window.bind("<Delete>", "-BUTTON_DELETE-")

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

            window["-COMBO_PROPERTY-"].Widget.configure(justify="center")

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

            move_window_center(window)

            timeout = None

            play_sound("pop")
