# 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 csv
import os
import PySimpleGUI as sg
from asset_image_icon_snactrac import *
from clear_events import *
from delete_entry_table import *
from format_history_admin import *
from get_data_table import *
from get_version import *
from move_window_center import *
from play_sound import *
from window_popup_general import *


# Handle history window interaction.
def window_history():

    timeout = 0

    selection = []

    headings = [
        "Date",
        "Time",
        "User",
        "Mode",
        "Action",
        "Description",
        "Total",
        "Old Balance",
        "New Balance",
        "Old Stock",
        "New Stock",
        "Profit",
    ]

    layout = [
        [
            sg.Frame(
                title=None,
                layout=[],
                size=(0, 20),
                pad=(0, 0),
            ),
        ],
        [
            sg.Push(),
            sg.Text(
                text="HISTORY",
                font=("Roboto", 19, "bold"),
                pad=(0, 0),
            ),
            sg.Push(),
        ],
        [
            sg.Push(),
            sg.Text(
                text="View, export table, or delete rows.",
                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=(14, 0),
                pad=(0, 0),
            ),
            sg.Table(
                values=format_history_admin(get_data_table("History")),
                headings=headings,
                col_widths=[12, 12, 49, 12, 20, 49, 12, 14, 14, 12, 12, 12],
                auto_size_columns=False,
                display_row_numbers=False,
                num_rows=30,
                font=("Roboto Mono", 3),
                justification="center",
                alternating_row_color="#465974",
                enable_events=True,
                pad=(0, 0),
                key="-TABLE_HISTORY-",
            ),
        ],
        [
            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="Export Table [END]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_EXPORT_TABLE-",
            ),
            sg.Button(
                button_text="Delete Selected Rows [DEL]",
                font=("Roboto", 13, "bold"),
                key="-BUTTON_DELETE_SELECTED_ROWS-",
            ),
            sg.Push(),
        ],
        [
            sg.FileSaveAs(
                file_types=(("CSV Files", "*.csv"),),
                initial_folder=os.path.join(os.path.expanduser("~"), "Downloads"),
                enable_events=True,
                key="-FILE_SAVE_AS_HISTORY-",
                visible=False,
            ),
        ],
    ]

    window = sg.Window(
        title="SnacTrac %s - History" % get_version(),
        size=(1905, 945),
        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 == "-TABLE_HISTORY-":

            if selection != values["-TABLE_HISTORY-"]:

                selections_current = set(values["-TABLE_HISTORY-"])

                selections_previous = set(selection)

                selections_added = selections_current - selections_previous

                selections_removed = selections_previous - selections_current

                if selections_added:

                    play_sound("click")

                elif selections_removed:

                    play_sound("scrape")

                selection = values["-TABLE_HISTORY-"]

            else:

                play_sound("nope")

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

            play_sound("tick")

            if window["-TABLE_HISTORY-"].Values == []:

                window_popup_general(
                    title="No Data Available",
                    text="There is no data to export.",
                    button_true="Okay",
                )

            else:

                if window_popup_general(
                    title="Confirm Export Table",
                    icon="choice",
                    text="Export table to a CSV file?",
                    button_false="Cancel",
                    button_true="Confirm",
                ):

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

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

            path = values["-FILE_SAVE_AS_HISTORY-"]

            csv_history = window["-TABLE_HISTORY-"].Values

            csv_history = [col[:-1] for col in csv_history]

            csv_history.insert(0, headings)

            with open(path, "w", newline="") as file:

                writer = csv.writer(file)

                writer.writerows(csv_history)

            window_popup_general(
                title="Table Exported",
                icon="success",
                text="The CSV file has been saved.",
                button_true="Okay",
            )

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

            play_sound("tick")

            if window["-TABLE_HISTORY-"].Values == []:

                window_popup_general(
                    title="No Data Available",
                    text="There are no rows to delete.",
                    button_true="Okay",
                )

            elif selection == []:

                window_popup_general(
                    title="Missing Selection",
                    text="At least one row must be selected.",
                    button_true="Okay",
                )

            else:

                if window_popup_general(
                    title="Confirm Delete Selection",
                    icon="choice",
                    text="Delete the current selection?",
                    button_false="Cancel",
                    button_true="Confirm",
                ):

                    del_history = [
                        window["-TABLE_HISTORY-"].Values[col][12] for col in selection
                    ]

                    for id in del_history:

                        delete_entry_table("History", "ID", id)

                    selection = []

                    window["-TABLE_HISTORY-"].update(
                        format_history_admin(get_data_table("History"))
                    )

                    window_popup_general(
                        title="Selection Deleted",
                        icon="success",
                        text="The selected rows have been deleted.",
                        button_true="Okay",
                    )

                    clear_events(window)

        if timeout == 0:

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

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

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

            move_window_center(window)

            timeout = None

            play_sound("pop")
