# 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 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 *


# Handle profile window interaction.
def window_profile(username):

    timeout = 0

    triggers = []

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

    layout = [
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 20),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Text(
                text="PROFILE",
                font=("Roboto", 19, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Push(),
            sg.Text(
                text="Manage account 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 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 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_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 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 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_PASSWORD-",
                pad=(0, 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="Ask Log Out:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(292, 0),
                pad=(0, 0),
            ),
            sg.Image(
                source=icon_info,
                pad=(5, 0),
                tooltip="Ask before logging out.",
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(5, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(2, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Combo(
                            values=[True, False],
                            default_value=str(bool(ask_log_out)),
                            size=(13, 1),
                            enable_events=True,
                            key="-COMBO_ASK_LOG_OUT-",
                            pad=(0, 0),
                            expand_x=False,
                            readonly=True,
                            font=("Roboto", 12),
                        ),
                    ]
                ],
                size=(368, 67),
                pad=(0, 0),
                border_width=0,
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 19),
                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 - Profile" % get_version(),
        size=(1053, 626),
        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 "store"

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

            if values["-COMBO_ASK_LOG_OUT-"] != ask_log_out:

                play_sound("tick")

                ask_log_out = values["-COMBO_ASK_LOG_OUT-"]

            else:

                play_sound("nope")

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

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

            play_sound("tick")

            if (values["-INPUT_NEW_PASSWORD-"] == "") != (
                values["-INPUT_CONFIRM_NEW_PASSWORD-"] == ""
            ):

                append_triggers(triggers, "-NEW_PASSWORD_BLANK-")

            if (
                " " in values["-INPUT_NEW_PASSWORD-"]
                or " " in values["-INPUT_CONFIRM_NEW_PASSWORD-"]
            ):

                append_triggers(triggers, "-NEW_PASSWORD_SPACE-")

            if (
                values["-INPUT_NEW_PASSWORD-"] != values["-INPUT_CONFIRM_NEW_PASSWORD-"]
                and values["-INPUT_NEW_PASSWORD-"] != ""
                and values["-INPUT_CONFIRM_NEW_PASSWORD-"] != ""
            ):

                append_triggers(triggers, "-NEW_PASSWORD_MISMATCH-")

            if (
                values["-INPUT_NEW_PASSWORD-"] == values["-INPUT_CONFIRM_NEW_PASSWORD-"]
                and values["-INPUT_NEW_PASSWORD-"] != ""
                and " " not in values["-INPUT_NEW_PASSWORD-"]
                and values["-INPUT_NEW_PASSWORD-"]
                == get_value_table("Users", "Username", username, "Password")
            ):

                append_triggers(triggers, "-NEW_PASSWORD_SAME-")

            elif (
                values["-INPUT_NEW_PASSWORD-"] == values["-INPUT_CONFIRM_NEW_PASSWORD-"]
                and values["-INPUT_NEW_PASSWORD-"] != ""
                and " " not in values["-INPUT_NEW_PASSWORD-"]
            ):

                set_value_table(
                    "Users",
                    "Username",
                    username,
                    "Password",
                    values["-INPUT_NEW_PASSWORD-"],
                )

                append_triggers(triggers, "-NEW_PASSWORD_CHANGED-")

            if values["-COMBO_ASK_LOG_OUT-"] != get_value_table(
                "Users", "Username", username, "Ask Log Out"
            ):

                set_value_table(
                    "Users",
                    "Username",
                    username,
                    "Ask Log Out",
                    values["-COMBO_ASK_LOG_OUT-"],
                )

                append_triggers(triggers, "-ASK_LOG_OUT_CHANGED-")

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

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

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

            if triggers == []:

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

            else:

                if "-NEW_PASSWORD_BLANK-" in triggers:

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

                if "-NEW_PASSWORD_SPACE-" in triggers:

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

                if "-NEW_PASSWORD_MISMATCH-" in triggers:

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

                if "-NEW_PASSWORD_SAME-" in triggers:

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

                if "-NEW_PASSWORD_CHANGED-" in triggers:

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

                if "-ASK_LOG_OUT_CHANGED-" in triggers:

                    window_popup_general(
                        title="Ask Log Out Set",
                        icon="success",
                        text='Your ask log out preference has been set to "%s".'
                        % ask_log_out,
                        button_true="Okay",
                    )

                triggers.clear()

        if timeout == 0:

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

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

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

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

            move_window_center(window)

            timeout = None

            play_sound("pop")
