# 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
import re
from append_history import *
from append_triggers import *
from asset_image_icon_info import *
from asset_image_icon_snactrac import *
from convert_money import *
from get_version import *
from move_window_center import *
from play_sound import *
from window_popup_general import *


# Handle event window interaction.
def window_event():

    timeout = 0

    triggers = []

    layout = [
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 20),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Text(
                text="EVENT",
                font=("Roboto", 19, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Push(),
            sg.Text(
                text="Record event to history.",
                font=("Roboto", 12, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 31),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(12, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="Title:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(119, 0),
                pad=(0, 0),
            ),
            sg.Image(
                source=icon_info,
                pad=(5, 0),
                tooltip="Name of what affected profit.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(7, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Input(
                            size=(20, 1),
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_TITLE-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(553, 65),
                pad=(0, 0),
                border_width=0,
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 24),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(12, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="Amount:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(37, 0),
                pad=(0, 0),
            ),
            sg.Image(
                source=icon_info,
                pad=(5, 0),
                tooltip="Amount impacting profit, positive or negative.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(7, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Input(
                            size=(20, 1),
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_AMOUNT-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(553, 65),
                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="Submit [ENTER]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_SUBMIT-",
            ),
            sg.Push(),
        ],
    ]

    window = sg.Window(
        title="SnacTrac %s - Event" % get_version(),
        size=(891, 537),
        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 == "-BUTTON_SUBMIT-":

            play_sound("tick")

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

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

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

                append_triggers(triggers, "-AMOUNT_BLANK-")

            else:

                try:

                    amount = convert_money(values["-INPUT_AMOUNT-"])

                    window["-INPUT_AMOUNT-"].update(convert_money(amount))

                except:

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

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

                    append_triggers(triggers, "-AMOUNT_INVALID-")

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

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

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

                append_triggers(triggers, "-TITLE_BLANK-")

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

                window["-INPUT_TITLE-"].update(
                    re.sub(r"\s{2,}", " ", values["-INPUT_TITLE-"]).strip()
                )

                append_triggers(triggers, "-TITLE_SPACE-")

            if triggers == []:

                if window_popup_general(
                    title="Confirm Event",
                    icon="choice",
                    text='Record "%s" for %s to history?'
                    % (values["-INPUT_TITLE-"], convert_money(amount)),
                    button_false="Cancel",
                    button_true="Confirm",
                ):

                    append_history(
                        mode="Admin",
                        action="Event",
                        description=values["-INPUT_TITLE-"],
                        profit=amount,
                    )

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

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

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

                    window_popup_general(
                        title="Event Recorded",
                        icon="success",
                        text='Recorded "%s" for %s to history.'
                        % (values["-INPUT_TITLE-"], convert_money(amount)),
                        button_true="Okay",
                    )

            else:

                if "-TITLE_BLANK-" in triggers:

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

                if "-TITLE_SPACE-" in triggers:

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

                if "-AMOUNT_BLANK-" in triggers:

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

                if "-AMOUNT_INVALID-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The amount must be a dollar amount.",
                        button_true="Okay",
                    )

                triggers.clear()

        if timeout == 0:

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

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

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

            move_window_center(window)

            timeout = None

            play_sound("pop")
