# 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
import sqlite3
from append_triggers import *
from append_users import *
from asset_image_icon_snactrac import *
from get_version import *
from move_window_center import *
from play_sound import *
from window_popup_admin_password import *
from window_popup_general import *


# Handle register window interaction.
def window_register():

    timeout = 0

    triggers = []

    usernames_reserved = ["admin", "guest"]

    layout = [
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 20),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Text(
                text="REGISTER",
                font=("Roboto", 19, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Push(),
            sg.Text(
                text="Create a new user account.",
                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=(9, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="First Name:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(214, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Input(
                            size=(14, 1),
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_FIRST_NAME-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(374, 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="Last Name:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(217, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Input(
                            size=(14, 1),
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_LAST_NAME-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(374, 65),
                pad=(0, 0),
                border_width=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="Username:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(231, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Input(
                            size=(14, 1),
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_USERNAME-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(374, 65),
                pad=(0, 0),
                border_width=0,
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 24),
                pad=(0, 0),
            ),
        ],
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(8, 0),
                pad=(0, 0),
            ),
            sg.Text(
                text="Password:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(236, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Input(
                            size=(14, 1),
                            password_char="●",
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_PASSWORD-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(374, 65),
                pad=(0, 0),
                border_width=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 Password:",
                font=("Roboto", 12),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[],
                size=(42, 0),
                pad=(0, 0),
            ),
            sg.Frame(
                title=None,
                layout=[
                    [
                        sg.Input(
                            size=(14, 1),
                            password_char="●",
                            justification="center",
                            font=("Roboto", 12),
                            key="-INPUT_CONFIRM_PASSWORD-",
                            pad=(0, 0),
                        ),
                    ]
                ],
                size=(374, 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 - Register" % get_version(),
        size=(891, 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")

            if any(
                filled != ""
                for filled in (
                    values["-INPUT_FIRST_NAME-"].replace(" ", ""),
                    values["-INPUT_LAST_NAME-"].replace(" ", ""),
                    values["-INPUT_USERNAME-"].replace(" ", ""),
                    values["-INPUT_PASSWORD-"].replace(" ", ""),
                    values["-INPUT_CONFIRM_PASSWORD-"].replace(" ", ""),
                )
            ):

                if window_popup_general(
                    title="Confirm Go Back",
                    icon="exit",
                    text="Are you sure you want to go back? This form will be lost.",
                    button_false="Cancel",
                    button_true="Confirm",
                ):

                    window.close()

                    return "welcome"

            else:

                window.close()

                return "welcome"

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

            play_sound("tick")

            if values["-INPUT_CONFIRM_PASSWORD-"] == "":

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

                append_triggers(triggers, "-CONFIRM_PASSWORD_BLANK-")

            if " " in values["-INPUT_CONFIRM_PASSWORD-"]:

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

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

                append_triggers(triggers, "-CONFIRM_PASSWORD_SPACE-")

            if values["-INPUT_PASSWORD-"] == "":

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

                append_triggers(triggers, "-PASSWORD_BLANK-")

            if " " in values["-INPUT_PASSWORD-"]:

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

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

                append_triggers(triggers, "-PASSWORD_SPACE-")

            if (
                values["-INPUT_PASSWORD-"] != values["-INPUT_CONFIRM_PASSWORD-"]
                and values["-INPUT_PASSWORD-"] != ""
                and values["-INPUT_CONFIRM_PASSWORD-"] != ""
            ):

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

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

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

                append_triggers(triggers, "-PASSWORD_MISMATCH-")

            if values["-INPUT_USERNAME-"] == "":

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

                append_triggers(triggers, "-USERNAME_BLANK-")

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

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

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

                append_triggers(triggers, "-USERNAME_SPACE-")

            else:

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

                cur = conn.cursor()

                cur.execute(
                    "SELECT COUNT(*) FROM Users WHERE Username = ?",
                    (values["-INPUT_USERNAME-"],),
                )

                count = cur.fetchone()[0]

                cur.close()

                conn.close()

                if (
                    count > 0
                    or values["-INPUT_USERNAME-"].lower() in usernames_reserved
                ):

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

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

                    append_triggers(triggers, "-USERNAME_SAME-")

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

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

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

                append_triggers(triggers, "-LAST_NAME_BLANK-")

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

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

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

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

                append_triggers(triggers, "-LAST_NAME_SPACE-")

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

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

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

                append_triggers(triggers, "-FIRST_NAME_BLANK-")

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

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

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

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

                append_triggers(triggers, "-FIRST_NAME_SPACE-")

            if triggers == []:

                if window_popup_admin_password():

                    append_users(
                        values["-INPUT_FIRST_NAME-"],
                        values["-INPUT_LAST_NAME-"],
                        values["-INPUT_USERNAME-"],
                        values["-INPUT_PASSWORD-"],
                    )

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

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

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

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

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

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

                    window_popup_general(
                        title="User Registered",
                        icon="success",
                        text="Your new account is ready to use.",
                        button_true="Okay",
                    )

            else:

                if "-FIRST_NAME_BLANK-" in triggers:

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

                if "-FIRST_NAME_SPACE-" in triggers:

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

                if "-LAST_NAME_BLANK-" in triggers:

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

                if "-LAST_NAME_SPACE-" in triggers:

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

                if "-USERNAME_BLANK-" in triggers:

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

                if "-USERNAME_SPACE-" in triggers:

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

                if "-USERNAME_SAME-" in triggers:

                    window_popup_general(
                        title="Username Unavailable",
                        text="Please choose a different username.",
                        button_true="Okay",
                    )

                if "-PASSWORD_BLANK-" in triggers:

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

                if "-PASSWORD_SPACE-" in triggers:

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

                if "-CONFIRM_PASSWORD_BLANK-" in triggers:

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

                if "-CONFIRM_PASSWORD_SPACE-" in triggers:

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

                if "-PASSWORD_MISMATCH-" in triggers:

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

                triggers.clear()

        if timeout == 0:

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

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

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

            move_window_center(window)

            timeout = None

            play_sound("pop")
