# 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_triggers import *
from asset_image_icon_info import *
from asset_image_icon_snactrac import *
from convert_money import *
from get_value_setting import *
from get_version import *
from move_window_center import *
from play_sound import *
from set_value_setting import *
from window_popup_general import *


# Handle settings window interaction.
def window_settings():

    timeout = 0

    triggers = []

    max_user_debt = get_value_setting("Max User Debt")

    guest_mode_enabled = get_value_setting("Guest Mode Enabled")

    launch_configuration = get_value_setting("Launch Program Setup Wizard")

    layout = [
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 20),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Text(
                text="SETTINGS",
                font=("Roboto", 19, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Push(),
            sg.Text(
                text="Manage program settings.",
                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=(8, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="New Admin Password:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(231, 0),
                pad=(0, 0),
            ),
            sg.Image(
                source=icon_info,
                pad=(5, 0),
                tooltip="Only required if changing admin password.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(7, 0),
                pad=(0, 0),
            ),
            sg.Input(
                size=(13, 1),
                password_char="●",
                justification="center",
                font=("Roboto", 12),
                key="-INPUT_NEW_ADMIN_PASSWORD-",
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 24),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(10, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="Confirm New Admin Password:",
                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="Must match new admin password.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(7, 0),
                pad=(0, 0),
            ),
            sg.Input(
                size=(13, 1),
                password_char="●",
                justification="center",
                font=("Roboto", 12),
                key="-INPUT_CONFIRM_NEW_ADMIN_PASSWORD-",
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 24),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(9, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="Max User Debt:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(398, 0),
                pad=(0, 0),
            ),
            sg.Image(
                source=icon_info,
                pad=(5, 0),
                tooltip="Denies a user access if exceeded.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(7, 0),
                pad=(0, 0),
            ),
            sg.Input(
                default_text=convert_money(max_user_debt),
                size=(13, 1),
                justification="center",
                font=("Roboto", 12),
                key="-INPUT_MAX_USER_DEBT-",
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 24),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(10, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="Guest Mode Enabled:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(263, 0),
                pad=(0, 0),
            ),
            sg.Image(
                source=icon_info,
                pad=(5, 0),
                tooltip="Allow guests to log in.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(7, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Combo(
                            values=[True, False],
                            default_value=str(guest_mode_enabled),
                            size=(13, 1),
                            enable_events=True,
                            key="-COMBO_GUEST_MODE_ENABLED-",
                            pad=(0, 0),
                            expand_x=False,
                            readonly=True,
                            font=("Roboto", 12),
                        ),
                    ]
                ],
                size=(368, 65),
                pad=(0, 0),
                border_width=0,
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 24),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(9, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="Launch Program Setup Wizard:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(47, 0),
                pad=(0, 0),
            ),
            sg.Image(
                source=icon_info,
                pad=(5, 0),
                tooltip="Prompt setup upon launch.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(7, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Combo(
                            values=[True, False],
                            default_value=str(launch_configuration),
                            size=(13, 1),
                            enable_events=True,
                            key="-COMBO_LAUNCH_CONFIGURATION-",
                            pad=(0, 0),
                            expand_x=False,
                            readonly=True,
                            font=("Roboto", 12),
                        ),
                    ]
                ],
                size=(368, 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="Save [ENTER]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_SAVE-",
            ),
            sg.Push(),
        ],
    ]

    window = sg.Window(
        title="SnacTrac %s - Settings" % get_version(),
        size=(1210, 804),
        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 == "-COMBO_GUEST_MODE_ENABLED-":

            if guest_mode_enabled != values["-COMBO_GUEST_MODE_ENABLED-"]:

                play_sound("tick")

                guest_mode_enabled = values["-COMBO_GUEST_MODE_ENABLED-"]

            else:

                play_sound("nope")

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

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

            if launch_configuration != values["-COMBO_LAUNCH_CONFIGURATION-"]:

                play_sound("tick")

                launch_configuration = values["-COMBO_LAUNCH_CONFIGURATION-"]

            else:

                play_sound("nope")

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

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

            play_sound("tick")

            if launch_configuration != get_value_setting("Launch Program Setup Wizard"):

                set_value_setting("Launch Program Setup Wizard", launch_configuration)

                append_triggers(triggers, "-LAUNCH_CONFIGURATION_CHANGED-")

            if guest_mode_enabled != get_value_setting("Guest Mode Enabled"):

                set_value_setting("Guest Mode Enabled", guest_mode_enabled)

                append_triggers(triggers, "-GUEST_MODE_ENABLED_CHANGED-")

            try:

                if max_user_debt != convert_money(values["-INPUT_MAX_USER_DEBT-"]):

                    if convert_money(values["-INPUT_MAX_USER_DEBT-"]) > 0:

                        max_user_debt = convert_money(values["-INPUT_MAX_USER_DEBT-"])

                        set_value_setting("Max User Debt", max_user_debt)

                        append_triggers(triggers, "-MAX_USER_DEBT_CHANGED-")

                    else:

                        append_triggers(triggers, "-MAX_USER_DEBT_LOW-")

                window["-INPUT_MAX_USER_DEBT-"].update(convert_money(max_user_debt))

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

            except:

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

                    append_triggers(triggers, "-MAX_USER_DEBT_BLANK-")

                else:

                    append_triggers(triggers, "-MAX_USER_DEBT_INVALID-")

                window["-INPUT_MAX_USER_DEBT-"].update(convert_money(max_user_debt))

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

            if (values["-INPUT_NEW_ADMIN_PASSWORD-"] == "") != (
                values["-INPUT_CONFIRM_NEW_ADMIN_PASSWORD-"] == ""
            ):

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

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

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

                append_triggers(triggers, "-NEW_ADMIN_PASSWORD_BLANK-")

            if (
                " " in values["-INPUT_NEW_ADMIN_PASSWORD-"]
                or " " in values["-INPUT_CONFIRM_NEW_ADMIN_PASSWORD-"]
            ):

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

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

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

                append_triggers(triggers, "-NEW_ADMIN_PASSWORD_SPACE-")

            if (
                values["-INPUT_NEW_ADMIN_PASSWORD-"]
                != values["-INPUT_CONFIRM_NEW_ADMIN_PASSWORD-"]
                and values["-INPUT_NEW_ADMIN_PASSWORD-"] != ""
                and values["-INPUT_CONFIRM_NEW_ADMIN_PASSWORD-"] != ""
            ):

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

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

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

                append_triggers(triggers, "-NEW_ADMIN_PASSWORD_MISMATCH-")

            if (
                values["-INPUT_NEW_ADMIN_PASSWORD-"]
                == values["-INPUT_CONFIRM_NEW_ADMIN_PASSWORD-"]
                and values["-INPUT_NEW_ADMIN_PASSWORD-"] != ""
                and " " not in values["-INPUT_NEW_ADMIN_PASSWORD-"]
                and values["-INPUT_NEW_ADMIN_PASSWORD-"]
                == get_value_setting("Admin Password")
            ):

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

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

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

                append_triggers(triggers, "-NEW_ADMIN_PASSWORD_SAME-")

            elif (
                values["-INPUT_NEW_ADMIN_PASSWORD-"]
                == values["-INPUT_CONFIRM_NEW_ADMIN_PASSWORD-"]
                and values["-INPUT_NEW_ADMIN_PASSWORD-"] != ""
                and " " not in values["-INPUT_NEW_ADMIN_PASSWORD-"]
            ):

                set_value_setting(
                    "Admin Password", values["-INPUT_NEW_ADMIN_PASSWORD-"]
                )

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

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

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

                append_triggers(triggers, "-NEW_ADMIN_PASSWORD_CHANGED-")

            if triggers == []:

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

                window_popup_general(
                    title="No Change",
                    text="No changes have been made to settings.",
                    button_true="Okay",
                )

            else:

                if "-NEW_ADMIN_PASSWORD_BLANK-" in triggers:

                    window_popup_general(
                        title="Incomplete Form",
                        text="Both password fields must be filled to set the new password.",
                        button_true="Okay",
                    )

                if "-NEW_ADMIN_PASSWORD_SPACE-" in triggers:

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

                if "-NEW_ADMIN_PASSWORD_MISMATCH-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The new password and new password confirmation must match.",
                        button_true="Okay",
                    )

                if "-NEW_ADMIN_PASSWORD_SAME-" in triggers:

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

                if "-NEW_ADMIN_PASSWORD_CHANGED-" in triggers:

                    window_popup_general(
                        title="Admin Password Set",
                        icon="success",
                        text="The new password has been set.",
                        button_true="Okay",
                    )

                if "-MAX_USER_DEBT_BLANK-" in triggers:

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

                if "-MAX_USER_DEBT_INVALID-" in triggers:

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

                if "-MAX_USER_DEBT_LOW-" in triggers:

                    window_popup_general(
                        title="Invalid Input",
                        text="The max user debt must be above zero.",
                        button_true="Okay",
                    )

                if "-MAX_USER_DEBT_CHANGED-" in triggers:

                    window_popup_general(
                        title="Max User Debt Set",
                        icon="success",
                        text="The max user debt has been set to %s."
                        % convert_money(max_user_debt),
                        button_true="Okay",
                    )

                if "-GUEST_MODE_ENABLED_CHANGED-" in triggers:

                    window_popup_general(
                        title="Guest Mode Enabled Set",
                        icon="success",
                        text='The guest mode preference has been set to "%s".'
                        % guest_mode_enabled,
                        button_true="Okay",
                    )

                if "-LAUNCH_CONFIGURATION_CHANGED-" in triggers:

                    window_popup_general(
                        title="Launch Program Setup Wizard Set",
                        icon="success",
                        text='The setup wizard preference has been set to "%s".'
                        % launch_configuration,
                        button_true="Okay",
                    )

                triggers.clear()

        if timeout == 0:

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

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

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

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

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

            move_window_center(window)

            timeout = None

            play_sound("pop")
